C++ 从 1 个字符转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17201590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:59:55  来源:igfitidea点击:

C++ convert from 1 char to string?

c++casting

提问by weeo

I need to cast only 1 charto string. The opposite way is pretty simple like str[0].

我只需要将 1 投射charstring. 相反的方式很简单,就像str[0].

The following did not work for me:

以下对我不起作用:

char c = 34;
string(1,c);
//this doesn't work, the string is always empty.

string s(c);
//also doesn't work.

boost::lexical_cast<string>((int)c);
//also doesn't work.

回答by Massa

All of

所有的

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

为我工作。

回答by Mallen

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

老实说,我认为铸造方法可以正常工作。既然没有,你可以试试stringstream。一个例子如下:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;