从 char(不是 char*)到 std::string 的首选转换 [英] Preferred conversion from char (not char*) to std::string

查看:29
本文介绍了从 char(不是 char*)到 std::string 的首选转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 char,一个普通的旧字符,我想把它变成一个 std::string.std::string(char) 当然不存在.我可以创建一个 char 数组并将其复制进去,我可以通过字符串流,或许多其他小的迂回路线.目前,我更喜欢 boost::lexical_cast,但对于这个简单的任务来说,即使这样也显得过于冗长.那么首选的方式是什么?

I have a char, a plain old character, that I would like to turn into an std::string. std::string(char) doesn't exist of course. I could create an char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast, but even that seems too verbose for this simple task. So what's the preferred way?

推荐答案

std::string 有一个接受数字和字符的构造函数.字符将重复给定的次数.因此,您应该使用:

std::string has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use:

std::string str(1, ch);

这篇关于从 char(不是 char*)到 std::string 的首选转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆