假设要将一系列数字读入到数组中,并允许用户在数组填满之前结束输入。一种方法是利用cin:
int n;
cin >> n;
如果用户输入一个单词而不是数字,将发生:
- n的值保持不变;
- 不匹配的输入将被保留在输入队列中;
- cin对象中的一个错误标记被设置;
对cin方法的调用将返回false。
返回false意味着可以用非数字输入来结束读取数字的循环。非数字输入设置错误标记意味着必须重置该标记,程序才能继续读取输入。clear()重置输入错误标记,同时也重置文件尾(EOF)。输入错误和文件尾都会导致cin返回false。
程序6.13
#include<iostream>
const int Max = 5;
int main()
{
using namespace std;
double fish[Max];
cout << "Please enter the weights of your fish.\n";
cout << "You may ennter 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 << ": ";
}
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of "
<< i << " fish\n";
cout << "Done.\n";
system("pause");
return 0;
}
程序6.14
#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();
while (cin.get() != '\n')
continue;
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";
system("pause");
return 0;
}
在程序6.14中,关键部分如下:
while (!(cin >> golf[i])) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter a number: ";
}
如果用户输入88,则cin表达式将为true,因此将一个值放到数组中;而表达式!(cin>>golf[i])为false,因此内部循环结束。然而,如果用户输入must i?,则cin表达式将为false,因此不会将任何值放到数组中;而表达式!(cin>>golf[i])将为true,因此进入内部的while循环。该循环的第一条语句使用clear()来重置输入,如果省略这条语句,程序将拒绝读取输入;接下来,程序在while循环中使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。另一种方法是读取到下一个空白字符,这样将每次删除一个单词,而不是一次删除整行。最后程序告诉用户,应输入一个数字。