Xåp*_* - 1 c++ string boolean concatenation char
我想做类似以下的事情:
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
Run Code Online (Sandbox Code Playgroud)
我见过的所有例子都使用cout,但我不想打印字符串; 只是存储它.
我该怎么做?如果可能的话,我想要一个分配给a char *和one 分配给a的例子std::string.
如果您的编译器足够新,它应该具有std::to_string:
string s = "Value of bool is: " + std::to_string(b);
Run Code Online (Sandbox Code Playgroud)
这当然会追加"1"(对true)或"0"(对false)到您的字符串,而不是"f"或"d"你想要的.原因是ther不是std::to_string一个bool类型的重载,因此编译器将其转换为整数值.
您当然可以分两步完成,首先声明字符串然后追加值:
string s = "Value of bool is: ";
s += b ? "f" : "d";
Run Code Online (Sandbox Code Playgroud)
或者像现在这样做,但明确地创建第二个std::string:
string s = "Value of bool is: " + std::string(b ? "f" : "d");
Run Code Online (Sandbox Code Playgroud)
编辑:如何char从a 获取指针std::string
这是通过该std::string::c_str方法完成的.但正如Pete Becker所指出的,你必须小心如何使用这个指针,因为它指向字符串对象内的数据.如果对象被破坏,那么数据和指针(如果已保存)现在将无效.
std::ostringstream s;
s << "Value of bool is: " << b;
std::string str(s.str());
Run Code Online (Sandbox Code Playgroud)
您可以使用std::boolalpha有"true"或"false"替代的int表示:
s << std::boolalpha << "Value of bool is: " << b;
Run Code Online (Sandbox Code Playgroud)
请注意,发布的代码几乎是正确的(不可能是+两个char[]):
std::string s = std::string("Value of bool is: ") + (b ? "t" : "f");
Run Code Online (Sandbox Code Playgroud)
要分配给char[]您可以使用snprintf():
char buf[1024];
std::snprintf(buf, 1024, "Value of bool is: %c", b ? 't' : 'f');
Run Code Online (Sandbox Code Playgroud)
或者只是std::string::c_str().
足够简单:
std::string s = std::string("Value of bool is: ") + (b ? "f" : "d");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6472 次 |
| 最近记录: |