#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;
}
如果用户输入88,则cin表达式将为true,因此将一个值放到数组中;而表达式!(cin>>golf[i])为false,因此内部循环结束。然而,如果用户输入must i?,则cin表达式将为false,因此不会将任何值放到数组中;而表达式!(cin>>golf[i])将为true,因此进入内部的while循环。该循环的第一条语句使用clear()来重置输入,如果省略这条语句,程序将拒绝读取输入;接下来,程序在while循环中使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。另一种方法是读取到下一个空白字符,这样将每次删除一个单词,而不是一次删除整行。最后程序告诉用户,应输入一个数字。
请问专家这里讲的“另一种方法是读取到下一个空白字符”这怎么编写代码啊?