读取一行,以空格分隔数字

之前在OJ上遇到一道题,给你一行数字,按空格隔开,但是不告诉你数字的数目,自己处理。一开始很懵,后来借助stringstream类成功解决,分享给大家。
(具体说明都写在注释里面了)

#include 
using namespace std;

int main()
{
	string inputstr;
	stringstream  inputss;
	string tempstr;	//临时string 
	int cnt = 0; 
	while(getline(cin, inputstr))
	{//获取一行输入存在inputstr中,包含空格 
	 
		inputss << inputstr;	//转存到inputss中
		while(inputss >> tempstr)
		{//开始对inputss中的所有子串进行操作,以空格为划分,存到tempstr中 
			stringstream tempss;	//创建一个临时的stringstream,为的是方便转换 
			tempss << tempstr;	 
			int val;
			tempss >> val;	//转换成数字输出 
			cout << val << endl;
			cnt++;
		}
		cout << "这一行一共有" << cnt << "个数字" << endl; 
	}								
	return 0;
} 

结果如下:
读取一行,以空格分隔数字_第1张图片

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