天天看點

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

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

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

方法一:判斷Enter鍵(用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 }      

『注:本文來自部落格園“小溪的部落格”,若非聲明均為原創内容,請勿用于商業用途,轉載請注明出處http://www.cnblogs.com/xiaoxi666/』