读取数字循环(遇非数字退出和跳过继续读取两种情况C++代码)

本文详细介绍了在C++代码中处理用户输入非数字情况的两种常见方法:一种是直接退出循环,另一种是跳过错误输入并提示用户重新输入。通过示例代码展示了如何实现这两种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在实际的人机交互式的代码中经常会出现要求输入数字,但是没有输入数字的情况,会出现几种情况?如下

int n;

cin >> n;

当用户输入了单词而非数字,则会出现以下4种情况:

1. n的值保持不变;

2. 输入的不匹配的单词留在内存队列中;

3. cin产生错误标志;必须使用clear()进行reset flag,否则程序将不会继续读取输入。

4. 返回false。

C++书中给出了“遇非数字退出”和“跳过继续读取”两种情况两种情况的经典代码:

情况一:非数字输入退出

// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
// get data
double fish[Max];
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]) {
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”;
return 0;
}

代码中:while (i < Max && cin >> fish[i])当cin读取非数字时,cin为0,while循环退出。

如果想跳过非数字的输入,提示用户重新输入则需要在代码中完成以下3个步骤:

1. Reset cin,从而cin可以重新读取输入;

2. 清除之前的错误输入;

3. 提示用户再次输入。

下面这个代码则诠释了上面3个步骤:

情况二:非数字输入提示重新输入

// 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;
}

while (!(cin >> golf[i]))

{
cin.clear();     // reset input
while (cin.get() != ‘\n’)
continue;       // get rid of bad input
cout << “Please enter a number: “;
}

如果输入为数字cin为true,!cin则为0,跳出while循环。如果cin非数字,则执行循环内部的3步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值