在实际的人机交互式的代码中经常会出现要求输入数字,但是没有输入数字的情况,会出现几种情况?如下
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步。