六一的部落格


关关难过关关过,前路漫漫亦灿灿。



string stream

定义了读写内存string对象的基本类型

完成内存string的IO


头文件

1#include <sstream>

字符串流

-
只读 istringstream 继承自istream
只写 ostringstream 继承自ostream
可读写 stringstream 继承自iostream

创建字符串流


默认初始化字符串流

1sstream strm;   

用字符串初始化字符串流

1sstream strm(s);

设置和获取sstream字符串

1strm.str();    // 返回strm中字符串的拷贝
2
3strm.str(s);    // 将s拷贝到strm中. 返回void

使用字符串流处理字符串

字符串

// 数据:人名 多个电话号码
morgan 2015552368 8625550123
drew 9735550131
lee 6095550132 2015550175 8005550000

处理输入

 1struct PersonInfo
 2{
 3    string name;
 4    vector<string> phones;
 5};
 6
 7string line, word;
 8vector<PersonInfo> people;
 9
10while (getline(cin, line))
11{
12    istringstream record(line);
13    PersonInfo info;   
14    record >> info.name;
15    while (record >> word)
16        info.phones.push_back(word);
17    people.push_back(info); 
18}

假定有两个函数valid和format, 用来校验和格式化电话号码. 尝试输出

 1for (const auto &entry : people)
 2{
 3    ostringstream formatted, badNums;
 4    for (const auto &nums : entry.phones)
 5    {
 6        if (!valid(nums))
 7            badNums << " " << nums;
 8        else
 9            formatted << " " << format(nums);
10    }
11    if (badNums.str().empty())
12        os << entry.name << " " << formatted.str() << endl;
13    else
14        cerr << "input error: " << entry.name << " invalid number(s) " << badNums.str() << endl;
15}

字符串流


string stream

定义了读写内存string对象的基本类型

完成内存string的IO


头文件

1#include <sstream>

字符串流

-
只读 istringstream 继承自istream
只写 ostringstream 继承自ostream
可读写 stringstream 继承自iostream

创建字符串流


默认初始化字符串流

1sstream strm;   

用字符串初始化字符串流

1sstream strm(s);

设置和获取sstream字符串

1strm.str();    // 返回strm中字符串的拷贝
2
3strm.str(s);    // 将s拷贝到strm中. 返回void

使用字符串流处理字符串

字符串

// 数据:人名 多个电话号码
morgan 2015552368 8625550123
drew 9735550131
lee 6095550132 2015550175 8005550000

处理输入

 1struct PersonInfo
 2{
 3    string name;
 4    vector<string> phones;
 5};
 6
 7string line, word;
 8vector<PersonInfo> people;
 9
10while (getline(cin, line))
11{
12    istringstream record(line);
13    PersonInfo info;   
14    record >> info.name;
15    while (record >> word)
16        info.phones.push_back(word);
17    people.push_back(info); 
18}

假定有两个函数valid和format, 用来校验和格式化电话号码. 尝试输出

 1for (const auto &entry : people)
 2{
 3    ostringstream formatted, badNums;
 4    for (const auto &nums : entry.phones)
 5    {
 6        if (!valid(nums))
 7            badNums << " " << nums;
 8        else
 9            formatted << " " << format(nums);
10    }
11    if (badNums.str().empty())
12        os << entry.name << " " << formatted.str() << endl;
13    else
14        cerr << "input error: " << entry.name << " invalid number(s) " << badNums.str() << endl;
15}