C++基础 - string流

istringstream 从string读取数据, ostringstream 向string写入数据,stringstream兼具二者。string流对象中保存一个string对象的副本。

// 个人信息类
class PersonInfo {
public:
    long long id;
    string name;
    vector phones;
};

   // istringstream 使用实例1,处理输入一行数据中的复合信息
    string line, phone;
    vector people;
    while( getline(cin, line) ) {
        PersonInfo person;
        istringstream is(line);
        is >> person.id;
        is >> person.name;
        while(is >> phone) {
            person.phones.push_back(phone);
        }
        people.push_back(person);
    }

istringstream的一个技巧处理字符串切割

void split(string& str, vector& vec) {
    istringstream is1(str);
    string word;
    vec.clear();
    while( is1 >> word ) {
        vec.push_back(word);
    }
}

    // istringstream 使用实例2,c++实现简单的单词切割
    string str("hello world, hello motherland!");
    vector words;
    split(str, words);

ostringstream 使用,当我们逐步构造输出,希望最后一起获取时,ostringstream 就很有用处,它可以帮我们先将内容“写入”到一个内存ostringstream中,最后一次获取。

    // ostringstream 使用,当我们逐步构造输出,希望最后一起获取时,ostringstream 就很有用处
    // 它可以帮我们先将内容“写入”到一个内存ostringstream中,最后一次获取。
    ostringstream os;
    os << 1; // person.id
    os << "lilei"; // person.name;
    cout << os.str() << endl;

参考

C++ primer中文版 第五版 第8章

你可能感兴趣的:(C++,C++基础,c++)