C++:stringstream格式化字符串

2023-05-16

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++:stringstream格式化字符串 的相关文章

随机推荐