C++:istringstream 的用法


摘自:http://www.3gtarena.com/danapeixunjishu/C__peixun/2048.html

今天看到了一個比較有用的c++的輸入輸出控制類。C++引入了ostringstream、istringstream、stringstream這三個類,要使用他們創建對象就必須包含<sstream>這個頭文件。

    istringstream類用於執行C++風格的串流的輸入操作。

    ostringstream類用於執行C風格的串流的輸出操作。

    strstream類同時可以支持C風格的串流的輸入輸出操作。

    istringstream的構造函數原形如下:

    istringstream::istringstream(string str);

    它的作用是從string對象str中讀取字符。

   

View Code
#include<iostream>

    #include<sstream>        //istringstream 必須包含這個頭文件

    #include<string>

    using namespace std;

    int main()

    {

    string str=“i an a boy”;

    istringstream is(str);

    string s;

    whileis》s)

    {

    cout《s《endl;

    }

    }

 

    輸出是:

    i

    am

    a

    boy 

摘自:http://www.cppblog.com/shyli/archive/2006/10/17/13758.html

View Code
istringstream對象可以綁定一行字符串,然后以空格為分隔符把該行分隔開來。

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    string str, line;
    while(getline(cin, line))
    {
        istringstream stream(line);
        while(stream>>str)
            cout<<str.c_str()<<endl;
    }    
    return 0;
}

測試:
input:
abc   df   e              efgeg      ffg

ouput:
abc
df
e
efgeg
ffg

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM