stringstring istringstream ostri

2018-02-19  本文已影响45人  Ginkgo

原文出处

下图详细描述了几种类之间的继承关系:

示意图.png
  1. istringstream是由一个string对象构造而来,从一个string对象读取字符。

  2. ostringstream同样是有一个string对象构造而来,向一个string对象插入字符。

  3. stringstream则是用于C++风格的字符串的输入输出的。

istringstream是由一个string对象构造而来,从一个string对象读取字符。
ostringstream同样是有一个string对象构造而来,向一个string对象插入字符。
stringstream则是用于C++风格的字符串的输入输出的。

    #include<iostream>  
    #include <sstream>   
    using namespace std;
    int main()
    {  
        string test = "-123 9.87 welcome to, 989, test!";  
        istringstream iss;//istringstream提供读 string 的功能  
        iss.str(test);//将 string 类型的 test 复制给 iss,返回 void   
        string s;  
        cout << "按照空格读取字符串:" << endl;  
        while (iss >> s){  
            cout << s << endl;//按空格读取string  
     }  
        cout << "*********************" << endl;  
      
        istringstream strm(test);   
        //创建存储 test 的副本的 stringstream 对象  
        int i;  
        float f;  
        char c;  
        char buff[1024];  
      
        strm >> i;  
        cout <<"读取int类型:"<< i << endl;  
        strm >> f;  
        cout <<"读取float类型:"<<f << endl;  
        strm >> c;  
        cout <<"读取char类型:"<< c << endl;  
        strm >> buff;  
        cout <<"读取buffer类型:"<< buff << endl;  
        strm.ignore(100, ',');  
        int j;  
        strm >> j;  
        cout <<"忽略‘,’读取int类型:"<< j << endl;  
      
        system("pause");  
        return 0;  
    }  
  1. 在istringstream类中,构造字符串流时,空格会成为字符串参数的内部分界;
  2. istringstream类可以用作string与各种类型的转换途径
  3. ignore函数参数:需要读取字符串的最大长度,需要忽略的字符
    代码测试:
#include<iostream>  
#include <sstream>   
#include <string>
using namespace std;
int main()
{
    ostringstream out;
    out.put('t');
    out.put('e');
    out << "st";
    cout << out.str() << endl;
    return 0;
}

注:如果一开始初始化ostringstream,例如ostringstream out("test"),那么之后put或者<<时的字符串会覆盖原来的字符,超过的部分在原始基础上增加。

stringstream同理,三类都可以用来字符串和不同类型转换。

上一篇 下一篇

猜你喜欢

热点阅读