筆試輸入一行個數未知的數字

昨天做了一個筆試,題目不是很難,但卻在輸入上卡了許久。輸入的要求是:
個數未知的一組數組

用例11 2 3 4 5
用例211 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
請按任意鍵繼續. . .

參考博客:
梳理下istringstream ostringstream stringstream的關係

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章