// 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]) {
//abd运算符表达式的左侧为false,则c++将不会判断右侧的表达式
//这里的表达式进行判定意味着cin输入放在数组中,如果i等于Max,则循环结束。
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";
// code to keep VC execution window open if q is entered
// if (!cin) // input terminated by non-numeric response
// {
// cin.clear(); // reset input
// cin.get(); // read q
// }
// cin.get(); // read end of line after last input
// cin.get(); // wait for user to press <Enter>
return 0;
}
Please enter the weights of your fish.
You may enter up to 5 fish <q to terminate>.
fish #1: 8
fish #2: 5
fish #3: 4
fish #4: 5
fish #5: q
5.5 = average weight of 4 fish
Done.
下面对上面的程序进行改进:
(1)重置cin以接受新的输入
(2)删除错误输入
(3)提示用户再输入
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
int golf[Max];
cout << "Please enter your golf scores.\n";
cout << "You must enter " << Max << " round.\n";
int i;
for (i = 0; i < Max; i++)
{
cout << "round #" << i+1 << " : ";
while ( !(cin >> golf[i] )){
cin.clear();
//使用clear()方法重置cin,如果省略这条语句,程序将拒绝继读取输入。
//cin.clear(); clear()函数不是清除输入,而是清除错误状态。
//标准库的IO类如果出错,会为自身设置错误状态,这时是不能继续输入/输出的。 所以要先clear错误状态。
while (cin.get() != '\n')
//使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。这种是方法时一次性删除整行
//这一句不停从输入缓冲区中读取已经输入的字符,直到读走'\n'。这其实就是要消耗掉输入缓冲区中刚才错误输入的剩余内容。
//具体原理见课本第17章
continue;
cout << "Please enter a number: ";
}
}
double total = 0.0;
for (i = 0; i < Max; i++)
total += golf[i];
cout << total / Max << " = average score "
<< Max << " round\n";
return 0;
}
You must enter 5 round.
round #1 : 8
round #2 : d
Please enter a number: 5
round #3 : 6
round #4 : 8
round #5 : 9
7.2 = average score 5 round