关于 C++中 输入多行不定数量数字 的思考

输入多行不定数量数字使用while(cin>>/* ? */)语句方法是不太方便的,一旦输入Ctrl-Z之后便结束输入,只能成功输入一组信息而不能继续输入之后的组。
在网上搜索了好多不同方法,下面找到了比较有效的方法。(经过改良,存在vector中(网上也有方法存在数组中的))
以下提供在 main 中和 header 中的处理方法:

在main中

以C++ Primer Exercise 3.36(b)(即比较vector)为例:

#include <iostream>
#include <vector>
#include <string>
#include <sstream> // std::istringstream
using namespace std;

int main()
{
    
    
	vector<int> vint1, vint2;
	string num1, num2;
	cout << " First vector:";
	getline(cin, num1);
	istringstream is1(num1);
	int i;
	while (is1 >> i)
		vint1.push_back(i);
	cout << "Second vector:";
	getline(cin, num2);
	istringstream is2(num2);
	int j;
	while (is2 >> j)
		vint2.push_back(j);
	if (vint1.size() != vint2.size())
		cout << "vint1 is unequal to vint2" << endl;
	else
	{
    
    
		int s=0;
		auto it1 = vint1.begin();
		auto it2 = vint2.begin();
		for (int k = 0; k != vint1.size(); k++)
		{
    
    
			if (*it1 == *it2) s++;
			++it1;
			++it2;
		}
		if (s == vint1.size())
			cout << "vint1 is equal to vint2" << endl;
		else cout << "vint1 is unequal to vint2" << endl;
	}
	return 0;
}

其中关键部分(L12-16)即

	getline(cin, num1);
	istringstream is1(num1);
	int i;
	while (is1 >> i)
		vint1.push_back(i);

这当中需要用库sstream来达成istringstream功能。
当然此时需要用while语句将其不断存入vector中。否则只会将getline后得到的string内容的第一个数字存入。

在Header中

以下定义了将一行整数存入vector中的函数 cinvec_int 和将一行浮点数存入 vector 的 cinvec_double

#ifndef CINVEC
#define CINVEC
#include <iostream>
#include <vector>
#include <string>
#include <sstream> // std::istringstream

std::vector<int> cinvec_int(std::string cin_int)
{
    
    
	getline(std::cin, cin_int);
	std::vector<int> vint;
	std::istringstream is(cin_int);
	int i;
	while (is >> i)
		vint.push_back(i);
	return vint;
}

std::vector<double> cinvec_double(std::string cin_double)
{
    
    
	getline(std::cin, cin_double);
	std::vector<double> vdou;
	std::istringstream is(cin_double);
	double i;
	while (is >> i)
		vdou.push_back(i);
	return vdou;
}
#endif // !CINVEC

See also

Teddy van Jerry 的导航页
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter3(第三章)
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter5(第五章)

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108169209