C++的输入输出流简单总结【字符串】

1、istringstream、ostringstream、stringstream 类介绍

(1)基于控制台的输入输出

 iostream对流进行读写,由istream和ostream派生。

(2)基于文件的输入输出

头文件为fstream,ifstream从文件中读取,由istream派生。ofstream写到文件中去,由ostream派生,fstream对文件进行读写,由iostream派生。

(3)基于字符串的输入输出

istringstream从string对象中读取,由istream派生,ostringstream写入string对象中,由ostream派生。stringstream对string对象进行读写,由iostream派生。

2、istringstream类

字符串对象的初始化

istringstream a("2371");

常用的成员函数

str():使istringstream对象返回一个string字符串 

比如这样:

istringstream a("2371");
cout<<a.str()<<endl;

应用1:把字符串类型的数据转换为其他类型

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <set>
#include <sstream>
using namespace std;
 
int main()
{
    istringstream a("1 2.33");
    //cout<<a.str()<<endl;
    string b;
    b = a.str();
    int x;
    double y;
    /*a >> x;
    a >> y;
    cout<<x<<endl;
    cout<<y<<endl;*/
 
    a >> y;
    a >> x;
 
    cout<<x<<endl;
    cout<<y<<endl;
 
    return 0;
}

应用2:把长字符串读入流中,再从流中把以空格分隔的单词读入字符串。

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <set>
#include <sstream>
using namespace std;
 
#define read() freopen("data.in", "r", stdin)
 
int main()
{
    //read();
    istringstream a;
    string b,str;
    while(getline(cin,b))
    {
        a.str(b);//把b中de字符串存入字符流中
        while(a >> str)//每次读取一个以空格分隔的单词存入str中
        {
            cout<<str<<endl;
        }
    }
    return 0;
}

3、istringstream类

用来往流中写入数据

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <set>
#include <sstream>
using namespace std;
 
#define read() freopen("data.in", "r", stdin)
 
int main()
{
    //read();
    ostringstream a("hello");
    cout<<a.str()<<endl;
 
    a.put('2');
    cout<<a.str()<<endl;
 
    a.put('233');
    cout<<a.str()<<endl;
 
    return 0;
}

应用: 字符串与其他数据类型的转换

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <set>
#include <sstream>
using namespace std;
 
#define read() freopen("data.in", "r", stdin)
 
int main()
{
    //read();
    //浮点型变成字符串
    double a = 233.233;
    string str1;
    string str2;
 
    stringstream b;
 
    b << a;
    b >> str1;
 
    cout<<str1<<endl;
 
    b.clear();
    //多次使用stringstream,要先清空下,不能使用stream.str("");否则下面输出10
 
    //char变string
    char str[10] = "hello";
     
    b << str;
    b >> str2;
     
    cout<<str2<<endl;
 
    b.clear();
 
    //string变int
    string str3 = "123";
    int c;
 
    b << str3;
    b >> c;
 
    cout<<c<<endl;
    //可以用sizeof(c)看一下,c已经变成了4个字节的整形啦。
    return 0;
}
原文地址:https://www.cnblogs.com/acmsummer/p/4352550.html