C++數據個數未知情況下的輸入方法


我們經常需要輸入一串數,而數據個數未知。這時候就不能以數據個數作為輸入是否結束的判斷標准了。

這種情況下,我們可以用以下兩種方法輸入數據。

方法一:判斷回車鍵(用getchar()=='\n'即可判斷)

 1 //以整數為例
 2 #include <iostream>
 3 #include <vector>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int main(){
 8     vector<int> v;
 9     int tmp;
10     while(cin>>tmp){
11         v.push_back(tmp);
12         if(getchar() == '\n') 13             break; 14     }
15     //輸出
16     for(int val:v){
17         cout<<val<<endl;
18     }
19     return 0;
20 }
 1 //以字符串為例
 2 #include <iostream>
 3 #include <vector>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int main(){
 8     vector<string> v;
 9     string tmp;
10     while(cin>>tmp){
11         v.push_back(tmp);
12         if(getchar() == '\n') 13             break; 14     }
15     //輸出
16     for(string val:v){
17         cout<<val<<endl;
18     }
19     return 0;
20 }

 

方法二:用istringstream流對象處理

 1 //以字符串為例
 2 #include<iostream>
 3 #include<sstream>       //istringstream
 4 #include<string>
 5 using namespace std;
 6 int main()
 7 {
 8     //string str="I like wahaha! miaomiao~";
 9     string str;
10     cin>>str;
11     istringstream is(str); 12     string s;
13     while(is>>s)
14     {
15         cout<<s<<endl;
16     }    
17 }
 1 //以整數為例(先將一行數當做string輸入,再進行轉換)
 2 #include<iostream>
 3 #include<sstream>       //istringstream
 4 #include<string>
 5 using namespace std;
 6 int main()
 7 {
 8     //string str="0 1 2 33 4 5";
 9     string str;
10     getline(cin,str);
11     istringstream is(str); 12     int s;//這樣就轉換為int類型了
13     while(is>>s)
14     {
15         cout<<s+1<<endl;//現在已經可以運算了
16     }
17 }

 


免責聲明!

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



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