s3l*_*lph 0 c++ string-formatting
目前我只知道将值插入C++字符串或C字符串的两种方法.
我所知道的第一种方法是使用std::sprintf()和C字符串缓冲区(char数组).
第二种方法是使用类似的东西"value of i: " + to_string(value) + "\n".
但是,第一个需要创建缓冲区,如果您只想将字符串传递给函数,则会导致更多代码.第二个产生长行代码,每次插入一个值时字符串都会被中断,这使代码更难读.
从Python我知道format()函数,使用如下:
"Value of i: {}\n".format(i)
大括号由格式中的值替换,并且.format()可以附加其他内容.
我真的很喜欢Python的方法,因为字符串保持可读性,不需要创建额外的缓冲区.在C++中有没有类似的方法呢?
在C++中格式化数据的惯用方法是使用输出流(std::ostream参考).如果希望格式化输出以a结尾std::string,请使用输出字符串流:
ostringstream res;
res << "Value of i: " << i << "\n";
Run Code Online (Sandbox Code Playgroud)
使用str()成员函数来收集结果字符串:
std::string s = res.str();
Run Code Online (Sandbox Code Playgroud)
这与输出格式化数据的方法相匹配:
cout << "Value of i: " << i << "\n";
Run Code Online (Sandbox Code Playgroud)