C语言通过snprintf对字符串进行格式化,格式化前需要首先对字符串的长度预估,如果长度大于了字符数组的大小,格式化字符串会被截断。
C++通过stringstream对字符串进行格式化:
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
stringstream sstream;
sstream << "hello, "; //格式化字符串,输入"hello, "
sstream << 88; //格式化字符串,输入88
string&& str = sstream.str();//通过str获得sstream中当前内容
cout << str << endl; //输出:hello, 88
return 0;
}
可以设置字符串的格式:
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
stringstream sstream;
sstream << hex << setw(4) << setfill('0') << 15; //设置为16进制,4个字符宽,补0
string&& str = sstr