C++ istringstream總結


問題描述:

假如有一行用空格隔開的字符串的話,如何提取出每一個字符串

比如輸入

abc def ghi

然后我們又需要存下來每一個字符串的話,需要怎么做。

方法一:雙指針算法。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     char str[1010];
 5     cin.getline(str, 1010);
 6     int len = strlen(str);
 7     //cout << len << endl;
 8     for (int i = 0; i < len; i++) {
 9         int j = i;
10         //每一次i循環的時候,都保證i是指向單詞的第一個位置
11         while (j < len && str[j] != ' ') { //只要j沒有走到終點  
12             //然后我們要找到當前這個單詞的最后一個位置    
13             j++;
14         }
15         //當while循環結束時,j就指向當前這個空格
16         //此時從i到j-1之間就是一個單詞 
17         //這道題的具體邏輯 
18         for (int k = i; k < j; k++) {
19             cout << str[k];
20         } 
21         cout << endl;
22         i = j;
23         //cout << j << endl; 
24     }
25     return 0;
26 }

運行結果:

 方法二:C++中的istringstream

具體用法如下:

 1 #include <bits/stdc++.h> 
 2 using namespace std;  
 3 int main()   {  
 4     string str = "aa bb cc dd ee";  
 5     istringstream is(str); //創建istringstream對象is
 6                           //並同時使is和字符串str綁定 
 7     string s;  
 8     while (is >> s) { //將從str中讀取到的字符串is寫入到字符串s 
 9         cout << s << endl;  
10     }  
11     return 0; 
12 }

運行結果:

 適用於istringstream的具體題目https://www.cnblogs.com/fx1998/p/12730320.html

 


免責聲明!

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



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