sstream


istringstream類用於執行C++風格的串流的輸入操作。是由一個string對象構造而來,從一個string對象讀取字符。 

ostringstream類用於執行C風格的串流的輸出操作。 同樣是有一個string對象構造而來,向一個string對象插入字符。

stringstream則是用於C++風格的字符串的輸入輸出的。 同時可以支持C風格的串流的輸入輸出操作。

初始化方法:

  1. stringstream stream;
    int a;
    stream << "12";
    stream >> a;
    cout << a << endl;

     

  2. stringstream stream("adfaf afagfagag");
    string a;
    stream >> a;
    cout << a << endl;

     

  3. string a = "aljfljfalf";
    stringstream stream(a);
    cout << stream.str() << endl;

     

 

 1 #include <sstream>
 2 using namespace std;
 3 int main()
 4 {
 5  stringstream stream;
 6     int a,b;
 7     stream << "080";//將“080”寫入到stream流對象中
 8     stream >> a;//將stream流寫入到a中,並根據a的類型進行自動轉換,"080" -> 80
 9     cout << stream.str() << endl;//成員函數str()返回一個string對象,輸出80
10     cout << stream.length() << endl;//2
11 }
 1 #include <sstream>
 2 using namespace std;
 3 int main()
 4 {
 5     stringstream stream("123 3.14 hello");//不同對象用空格隔開,默認根據空格進行划分  
 6     double a;
 7     double b;
 8     string c;
 9     //將對應位置的內容提取出來寫到對應的變量中
10     //如果類型不同,自動轉換
11     stream >> a >> b >> c;//輸出 1233.14hello
12     cout << a << b << c;
13     stream.clear();
14     return 0;
15 }

str()和clear()

stream用完之后,其內存和標記仍然存在,需要用這兩個函數來初始化。

clear()只是清空而是清空該流的錯誤標記,並沒有清空stream流(沒有清空內存);

str(“”)是給stream內容重新賦值為空。

一般clear和str(“”“”)結合起來一起用。

 1 #include <sstream>
 2 #include <cstdlib>//用於system("PAUSE")
 3 using namespace std;
 4 int main()
 5 {
 6     stringstream stream;
 7     int a,b;
 8     stream << "80";
 9     stream >> a;
10     cout << stream.str() << endl;//此時stream對象內容是"80",不是空的
11     cout << stream.str().length() << endl;//此時內存為2byte
12     
13     //此時再將新的"90"寫入進去的話,會出錯的,因為stream重復使用時,沒有清空會導致錯誤。
14     //如下:
15     stream << "90";
16     stream >> b;
17     cout << stream.str() << endl;//還是80
18     cout << b << endl;//1752248,錯了,沒有清空標記,給了b一個錯誤的數值
19     cout << stream.str().length() << endl;//還是2bytes
20     
21     //如果只用stream.clear(),只清空了錯誤標記,沒有清空內存
22     stream.clear();
23     stream << "90";
24     stream >> b;
25     cout << b << endl;//90
26     cout << stream.str() <<endl;//變成90
27     cout << stream.str().length() << endl;//4,因為內存沒有釋放,2+2 = 4bytes
28     
29     //stream.clear() 和 stream.str("")都使用,標記和內存都清空了
30     stream << "90";
31     stream >> b;
32     cout << b << endl;
33     cout << stream.str() << endl;//90
34     cout << stream.str().length() << endl;//2bytes
35     
36     system("PAUSE");
37     return 0;
38 }

 


免責聲明!

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



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