以下语句将所有类型的输出作为单个文本字符串通过管道传输到控制台
std::cout << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms.";
我们可以使用相同的语法在字符串变量中构建字符串吗?它是怎么做到的?
最佳答案
#include <sstream>
std::ostringstream ss;
ss << "Hi, my name is " << name_as_string;
ss << " and I am " << age_as_int << " years old, while weighing ";
ss << weight_as_double << " kilograms.";
std::string str = ss.str();
您还可以将 std::istringstream
用于多输入,将 std::stringstream
用于输入和输出。
std::string str = "1 2 3 4 5";
std::istringstream ss(str);
int i;
while( ss >> i) {
std::cout << i;
}
关于c++ - 你能以类似于 std::cout 的方式创建一个字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042791/