#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()来读取行尾之前的所有输入,从而删除这一行中的错误输入。另一种方法是读取到下一个空白字符,这样将每次删除一个单词,而不是一次删除整行。最后程序告诉用户,应输入一个数字。
请问专家这里讲的“另一种方法是读取到下一个空白字符”这怎么编写代码啊?
【以下回答由 GPT 生成】
在C++中,可以使用以下方法来读取到下一个空白字符:
while (cin.peek() != ' ')
cin.ignore();
在每次循环中,cin.peek()
函数用于查看输入流中下一个字符而不将其取走。如果下一个字符不是空白字符,则调用cin.ignore()
函数来忽略掉该字符。这样,循环会一直执行,直到读取到下一个空白字符位置为止。
需要注意的是,cin.peek()
函数可以保留输入流中的空白字符,所以不需要再使用cin.ignore()
函数来忽略掉空白字符。
以下是将该方法插入到你的代码中的示例:
#include<iostream>
const int Max = 5;
int main()
{
using namespace std;
//获取数据
int golf[Max];
cout << "请输入您的高尔夫成绩。\n";
cout << "您必须输入 " << Max << " 轮。\n";
int i;
for (i = 0; i < Max; i++)
{
cout << "第 " << i + 1 << " 轮: ";
while (!(cin >> golf[i])) {
cin.clear();
while (cin.get() != ' ')
continue;
cout << "请输入一个数字: ";
}
}
//计算平均值
double total = 0.0;
for (i = 0; i < Max; i++)
total += golf[i];
//报告结果
cout << total / Max << " = 平均分 " << Max << " 轮\n";
system("pause");
return 0;
}
请注意,这种方法仅适用于读取到下一个空白字符的情况。如果你需要读取到下一个特定字符之类的需求,可以将上述代码中的' '
替换为所需的字符。
希望这能帮助到你!如果还有其他问题,请随时提问。