机试输入读取技巧(持续更新中)

情况1

输入:
1 2 3
3 6 5 2 5
7 7 55
1

如上可看出输入每一行的数字个数是未知的,需求是,每一行的数据为一个处理单元。

方法:利用stringstream将getline读取的一行数据,重新将行中的数据赋值给对应类型的变量。省去了删去空格与类型转换的操作。如果输入为string,例如:可以将下方的int改为string.

输入:
ac bc dd
apple pear banana
merry christmas
#include 
#include 
#include 
#include 
#include 
using namespace std;


int main(){
    //获取控制台端输入
	//每一行为一个输入单元
	string str;
	int num;
	
	while (getline(cin, str)){
		stringstream ss(str);
		int num;
		while (ss >> num){
			cout << num << ' ';
		}
		cout << endl;
	}
	return 0;
}

 

你可能感兴趣的:(C++)