sstream类的操作

需要头文件<sstream>

1 stringstream

将字符串放入sstream中

    stringstream sstream;
    sstream << "abcd" ;
    cout << sstream.str() << endl;

1.1 数据类型转换:将int类型转换为string类型

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    stringstream sstream;
    string str;
    int value = 10;
    sstream << value;
    sstream >> str;
    cout << str << endl;
    return 0;
}
View Code

1.2 stringstream的清空

清空有两种方式,sstream.str("")和clear();

同一类型中清空数据用str(""),如下

    stringstream sstream;
    sstream << "abcd" ;
    cout << sstream.str() << endl;
    // 输出为abcd
    sstream.str("");
    sstream << "play";
    cout << sstream.str() << endl;
    //输出为play

进行多次类型转换时,用clear()

    stringstream sstream;
    string str;
    int x;
    //string 类
    sstream << "abcd" ;
    sstream >> str;
    cout << str <<endl;
    // 输出为abcd
    
    sstream.clear();
    
    //int 类
    sstream << 123;
    sstream >> x;
    cout << x << endl;
    //输出为123

2 istringstream

istringstream是获取一行的字符串

    string str = "play a game";
    istringstream isstream(str);
    string ss;
    while(isstream >> ss){
        cout << ss <<endl;
    }
    //输出为
    //play
    //a
    //game

可以用getline(cin,str)输入一行字符串

猜你喜欢

转载自www.cnblogs.com/imnotGemini/p/13192636.html