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

wee*_*eeo 108 c++ casting

我真的没有找到任何接近的答案......

相反的方式非常简单,如str [0]

但我只需要将1个字符串转换为字符串...

像这样:

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 return null
Run Code Online (Sandbox Code Playgroud)

Mas*_*ssa 170

所有的

string s(1, c); std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)

std::cout << string(1, c) << std::endl;
Run Code Online (Sandbox Code Playgroud)

string s; s.push_back(c); std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)

为我工作.

  • @doctorram不!1.你使用的引号是无效的C++; 2.即使你的意思是`s =""+ c`它只是UB,因为它并不意味着"将空字符串连接到字符`c`",它意味着"指向空字符串的某些副本的指针,由`c`的数值(绝对不是你想要的); 3.如果你的意思是`s =""s + c`,它仍然比`s {1,c}更长......(和你一样)必须写`使用std :: literals;`某处...... (13认同)
  • 对不起,我的意思是:string s = string()+'a'; (9认同)
  • 最短的方法是:string s =""+ c; (3认同)
  • @doctorram,更短的方法是 `string s = {c};` 或 `string s({c});` 或 `string s{c};` https://ideone.com/eFZTFY (3认同)

Mal*_*len 8

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

#include <sstream>
#include <string>
stringstream ss;
string target;
char mychar='a';
ss << mychar;
ss >> target;
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这个特定的字符串构造函数不起作用的事实与真正的问题有关. (2认同)

arm*_*ali 5

无论char您拥有多少变量,此解决方案都将起作用:

char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};
Run Code Online (Sandbox Code Playgroud)