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

新手上路,请多包涵

我只需要将 1 char 转换为 string 。相反的方法很简单,比如 str[0]

以下对我不起作用:

 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.

原文由 weeo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 457
2 个回答

所有的

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

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

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

为我工作。

原文由 Massa 发布,翻译遵循 CC BY-SA 4.0 许可协议

老实说,我认为铸造方法会很好。既然没有,你可以试试 stringstream。下面是一个例子:

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

原文由 Mallen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题