昨天做了一個筆試,題目不是很難,但卻在輸入上卡了許久。輸入的要求是:
個數未知的一組數組
用例1:
1 2 3 4 5
用例2:
11 22 33 44 55 66 77 88
要把輸入的數字提取出來,保存在vector中,方便後面對數據進行操作。
方法1、判斷數字後面的字符是否是回車\n
方法2、用string流(istringstream)來處理輸入
代碼實現:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// 輸入一行個數未知的數字,方法1:判斷數字後面的字符是否是回車\n
void test01(){
vector<int> v;
int num;
while (cin >> num){
v.push_back(num);
char ch = getchar();
if (ch == '\n') break;
}
for (int i : v){
cout << i << " ";
}
cout << endl;
}
// 輸入一行個數未知的數字,方法2:用string流來接收數據
void test02(){
string str;
getline(cin, str);
istringstream iss(str);
vector<int> ret;
int tmp;
while (iss >> tmp){
ret.push_back(tmp);
}
for (int i : ret){
cout << i << " ";
}
cout << endl;
}
int main(){
//test01();
test02();
system("pause");
return 0;
}
運行結果:
11 22 33 44 55 66 77 88
11 22 33 44 55 66 77 88
請按任意鍵繼續. . .