内核格式化(将格式化信息写入string对象)788

sstream定义了一个从ostream派生来的ostringstream类,可以将格式化信息写入string对象,在格式化文本进入缓冲区的时候,

如果有必要,将使用动态分配内存来扩大缓冲区。ostringstream有一个成员函数str(),可以返回被初始化为缓冲区内容的字符串。见例:

// strout.cpp -- incore formatting (output)
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    using namespace std;
    ostringstream outstr; // manages a string stream
    string hdisk;
    cout << "What's the name of your hard disk? ";
    getline(cin, hdisk);
    int cap;
    cout << "What's its capacity in GB? ";
    cin >> cap;
    // write formatted information to string stream
    outstr << "The hard disk " << hdisk << " has a capacity of "
           << cap << " gigabytes.\n";
    string result = outstr.str(); // save result
    cout << result; // show contents
    return 0;
}

上面的代码中,把hdisk和cap等信息写入outstr中,利用str函数返回缓冲区内容的字符串结果,然后用cout输出result。


istringstream类允许使用istream类的方法读取istringstream对象中的内容。

// strin.cpp -- formatted reading from a char array
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    using namespace std;
    string lit = "It was a dark and stormy day, and "
                " the full moon glowed brilliantly. ";
    istringstream instr(lit); // use buf for input
    string word;
    while (instr >> word) // read a word a time
    cout << word << endl;
    return 0;
}

输出


可以看出,instr在获取word的内容时,遇到空格就停止。与cin相同

换成:

 while (getline(instr,word))

输出


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值