【C++】提醒用户输入数字,如何处理用户错误输入?(优秀的编程思想)

你提醒用户一定要输入5个数字

但是用户故意输入2个数字,一个其他字符,再输入其他数字, 你该怎么处理这样的普遍情况?

解决办法:

用到cin的bool特性!

#include <iostream>
const int Max = 5;
int main()
{
	using namespace std;
	int golf[Max];
	cout << "请输入的分数:\n";
	cout << "你必须输入" << Max << "个数\n";
	int i;
	for (i = 0; i < Max; i++)
	{
		cout << "得分#" << i + 1 << ": ";
		while (!(cin >> golf[i]))
		{
			cin.clear();
			while (cin.get() != '\n')
			{
				continue;
			}//跳过错误输入
			cout << "请输入一个数字:";
		}
	}
	double total = 0.0;
	for (i = 0; i < Max; i++)
	{
		total += golf[i];	
	}
    cout << total / Max << "平均值" << Max << " 重量\n";
	system("pause");
	return 0;

}

运行结果 如下:

核心代码:

		while (!(cin >> golf[i]))
		{
			cin.clear();
			while (cin.get() != '\n')
			{
				continue;
			}//跳过错误输入
			cout << "请输入一个数字:";
		}

猜你喜欢

转载自blog.csdn.net/qq_15698613/article/details/84933435