当前位置:嗨网首页>书籍在线阅读

23-内核格式化

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

17.5 内核格式化

iostream族(family)支持程序与终端之间的I/O,而fstream族使用相同的接口提供程序和文件之间的I/O。C++库还提供了sstream族,它们使用相同的接口提供程序和string对象之间的I/O。也就是说,可以使用于cout的ostream方法将格式化信息写入到string对象中,并使用istream方法(如getline())来读取string对象中的信息。读取string对象中的格式化信息或将格式化信息写入string对象中被称为内核格式化(incore formatting)。下面简要地介绍一下这些工具(string的sstream族支持取代了char数组的strstream.h族支持)。

头文件sstream定义了一个从ostream类派生而来的ostringstream类(还有一个基于wostream的wostringstream类,这个类用于宽字符集)。如果创建了一个ostringstream对象,则可以将信息写入其中,它将存储这些信息。可以将可用于cout的方法用于ostringstream对象。也就是说,可以这样做:

ostringstream outstr;
double price = 380.0;
char * ps = " for a copy of the ISO/EIC C++ standard!";
outstr.precision(2);
outstr << fixed;
outstr << "Pay only CHF " << price << ps << endl;

格式化文本进入缓冲区,在需要的情况下,该对象将使用动态内存分配来增大缓冲区。ostringstream类有一个名为str()的成员函数,该函数返回一个被初始化为缓冲区内容的字符串对象:

string mesg = outstr.str(); // returns string with formatted information

使用str()方法可以“冻结”该对象,这样便不能将信息写入该对象中。

程序清单17.21是一个有关内核格式化的简短示例。

程序清单17.21 strout.cpp

// 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;
}

下面是程序清单17.21中程序的运行情况:

What's the name of your hard disk? Datarapture
What's its capacity in GB? 2000
The hard disk Datarapture has a capacity of 2000 gigabytes.

istringstream类允许使用istream方法族读取istringstream对象中的数据,istringstream对象可以使用string对象进行初始化。

假设facts是一个string对象,则要创建与该字符串相关联的istringstream对象,可以这样做:

istringstream instr(facts); // use facts to initialize stream

这样,便可以使用istream方法读取instr中的数据。例如,如果instr包含大量字符格式的整数,则可以这样读取它们:

int n;
int sum = 0;
while (instr >> n)
    sum += n;

程序清单17.22使用重载的>>运算符读取字符串中的内容,每次读取一个单词。

程序清单17.22 strin.cpp

// 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;
}

下面是程序清单17.22中程序的输出:

It
was
a
dark
and
stormy
day,
and
the
full
moon
glowed
brilliantly.

总之,istringstream和ostringstream类使得能够使用istream和ostream类的方法来管理存储在字符串中的字符数据。