不使用sprintf或to_string将值插入字符串

Insert values into a string without using sprintf or to_string

本文关键字:string 插入 字符串 to sprintf      更新时间:2023-10-16

目前我只知道两种方法来插入值到c++字符串或C字符串

我知道的第一个方法是使用std::sprintf()和c字符串缓冲区(字符数组)。

第二种方法是使用类似"value of i: " + to_string(value) + "n"的东西。

但是,第一个需要创建一个缓冲区,如果您只是想将字符串传递给函数,则会导致更多的代码。第二种方法产生很长的代码行,其中每次插入值时字符串都会被中断,这使得代码更难阅读。

从Python我知道format()函数,它是这样使用的:

"Value of i: {}n".format(i)

用format中的值替换大括号,并可以追加.format()

我非常喜欢Python在这方面的方法,因为字符串保持可读,并且不需要创建额外的缓冲区。在c++中有类似的方法吗?

c++中格式化数据的惯用方法是使用输出流(std::ostream参考)。如果希望格式化的输出以std::string结尾,请使用输出字符串流:

ostringstream res;
res << "Value of i: " << i << "n";

使用str()成员函数获取结果字符串:

std::string s = res.str();

这与格式化输出数据的方法相匹配:

cout << "Value of i: " << i << "n";