不使用sprintf或to_string将值插入字符串
Insert values into a string without using sprintf or to_string
目前我只知道两种方法来插入值到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";
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 在 std::string 的末尾插入换行符
- 如何在矢量"[i]"中插入*字符<string>?[C++]
- 如何将带有前导零的整数插入到 std::string 中
- 在使用 std::string 和 std::vector 将值插入 std::map 时遇到问题
- 在“std::map”中插入一个“int”值,该值应该存储“std::string”
- 列表数组<string>,插入字符串行为奇怪
- 拆分 std::string 并插入到 std::set 中
- vector<string> 为空,而已插入某些字符串
- 将数据从两种不同的数据结构插入 std::map <std::string, int> mymap 并通过套接字发送
- 从" map<string, map<string ,string> > "插入到 wxListCtrl
- ^(插入符号)在C++中是什么意思,就像在String^中一样
- 在c++中从vector向string插入一个字符
- 如何在std::string中插入无符号char*变量
- 使用插入<string>函数时从字符到常量字符的转换无效
- std::string 搜索字符串中的数字并在前后插入空格
- 在映射中插入 std::string 和指向对象的共享指针
- 插入到属于 map <int、set > 的集合中<string>
- 如何将数据插入地图<字符串,设置<string>> C++?