c++输入检查

这篇博客探讨了在C++中如何处理istream对象的输入检查,特别是当用户输入的数据与预期类型不匹配时。通过示例代码展示了当输入非数字时如何终止循环并重新设置输入状态,以及如何进行用户输入检查,确保输入的数据类型匹配并能正确处理无效输入。
摘要由CSDN通过智能技术生成

istream类重载了抽取运算符<< ,>>,>>运算符可以将字符类型的数据转换为所需的数据类型。在执行cin >>variable;语句时,cin对象将标准输入表示为字符流,然后<<运算符将字符类型的数据转换为所需的数据类型。当遇到无法转换的情况时,比如对于一个int类型的变量a,却输入字符H,这种情况下,<<运算符将不会改变变量a的值,并返回0,并且设置标识符无效,此后不再允许用户输入。如果用户需要再次输入,则需要设置标识符为有效才可。

//在使用cin获取键盘输入时,如下所示,cin会根据变量golf的类型匹配相应的数据,
//如果类型无法匹配,则cin会返回False报错
int golf[Max];
cin >> golf[i];

11.1 非数字终止循环

当然这个也还有用武之地,可以被放在循环条件中来终止循环。(需要注意的是,循环终止后不再允许用户输入,即使调用cin>>也没用;如需要用户输入,则需要设置标识符为有效才可)如下例子:

code:

// File name:           cinfish.cpp
// Last modified Date:  2021年11月21日11点28分
// Last Version:        V1.0
// Descriptions:        非数字输入终止循环
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main()
{
	using namespace std;
	// get data
	double fish[Max];
	char x;
	cout << "Please enter the weights of your fish.\n";
	cout << "You may enter up to " << Max
		<< " fish <q to terminate>.\n";
	cout << "fish #1: ";
	int i = 0;
	while (i < Max && cin >> fish[i]) {//在这里,如果输入为字符,那么第二个条件会为0,将不会再执行循环体的内容
		if (++i < Max)
			cout << "fish #" << i + 1 << ": ";
	}
	// calculate average
	double total = 0.0;
	for (int j = 0; j < i; j++)
		total += fish[j];
	// report results
	if (i == 0)
		cout << "No fish\n";
	else
		cout << total / i << " = average weight of "
		<< i << " fish\n";
	cout << "Done.\n";

	//如果再需要输入的话
	cin.clear(); // reset input 如果没有这一句的话,后面就直接运行完成,不会请求用户输入
	//这一句是吃掉结束循环的那个字符
	cin.get();
	//这一句是吃掉那个结束字符后面的回车
	cin.get();
	cout << "请输入一个测试字符:";
	x = cin.get();
	cout << x<<endl;
	return 0;
}

运行结果:

Please enter the weights of your fish.
You may enter up to 5 fish <q to terminate>.
fish #1: 2.9
fish #2: a
2.9 = average weight of 1 fish
Done.
请输入一个测试字符:r
r

D:\Prj\C++\C++_Learning\cinfish_cin_Input_inspection\Debug\cinfish_cin_Input_inspection.exe (进程 14760)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

11.2 用户输入检查

如果用户输入与变量类型不匹配,就提示用户输入类型匹配的数据并处理掉那些不匹配的数据。

code:

// File name:           user_Input_inspection
// Last modified Date:  2021年11月21日11点33分
// Last Version:        V1.0
// Descriptions:        用户输入检查

// cingolf.cpp -- non-numeric input skipped
#include <iostream>
const int Max = 5;
int main()
{
	using namespace std;
	// get data
	int golf[Max];
	cout << "Please enter your golf scores.\n";
	cout << "You must enter " << Max << " rounds.\n";
	int i;

	for (i = 0; i < Max; i++)
	{
		cout << "round #" << i + 1 << ": ";
		//**************************用户输入检查的核心部分开始**************************//
		while (!(cin >> golf[i])) {//如果输入类型不匹配,则执行循环体
			cin.clear(); // reset input设置标志位为有效
			while (cin.get() != '\n')  //删除没有用的输入
				continue; // get rid of bad input
			cout << "Please enter a number: ";
		}
		//**************************用户输入检查的核心部分结束**************************//
	}
	// calculate average
	double total = 0.0;
	for (i = 0; i < Max; i++)
		total += golf[i];
	// report results
	cout << total / Max << " = average score "
		<< Max << " rounds\n";
	return 0;
}

运行结果:

Please enter your golf scores.
You must enter 5 rounds.
round #1: 5
round #2: 6
round #3: 7
round #4: 88
round #5: a
Please enter a number: 19
25 = average score 5 rounds

D:\Prj\C++\C++_Learning\user_Input_inspection\Debug\user_Input_inspection.exe (进程 6568)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值