假设要编写一个将一系列数字读入到数组的程序,并准许用户在数组填满之前结束输入。一种方法是利用cin。请看下面的代码:
如果用户输入一个单词,而不是一个数字,情况将如何呢?发生这种类型不匹配的情况时,将发生4中情况:
运行结果:
运行结果:
int n;
cin>>n;
如果用户输入一个单词,而不是一个数字,情况将如何呢?发生这种类型不匹配的情况时,将发生4中情况:
n的值保持不变
不匹配的输入将被留在输入队列中
cin对象中的一个错误标记被设置
对cin方法的调用将放回false(如果被转换为bool类型)
例子:
#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 <1 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;
}
运行结果:
Please enter the weights of your fish.
You may enter up to 5 fish <1 to terminate>.
fish #1: 30
fish #2: 35
fish #3: 25
fish #4: 40
fish #5: q
32.5 = average weight of 4 fish
Done.
Press any key to continue
再看个例子,程序要求用户提供5个高尔夫得分,以计算平均成绩。如果用户输入非数字输入,程序将拒绝,并要求用户继续输入数字。可以看到,可以使用cin输入表达式的值来测试输入是不是数字。程序发现用户输入了错误的内容时,应采取3个步骤:
重置cin以接受新的输入。
删除错误输入。
提示用户再输入。
代码:
// 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];
}
cout<<total/Max<<" = average score "
<<Max<<" rounds\n";
return 0;
}
运行结果:
Please enter your golf scores.
You must enter 5 rounds.
round #1: 88
round #2: 87
round #3: must i?
Please enter a number: 103
round #4: 94
round #5: 86
91.6 = average score 5 rounds
Press any key to continue