C++数据个数未知情况下的输入方法

我们经常需要输入一串数,而数据个数未知。这时候就不能以数据个数作为输入是否结束的判断标准了。

这种情况下,我们可以用以下两种方法输入数据。

方法一:判断回车键(用getchar()==' '即可判断)

 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() == '
')
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() == '
')
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/』
原文地址:https://www.cnblogs.com/xiaoxi666/p/7435980.html