C++ 在循环c+;中不断询问用户输入+;
我正在制作一个程序,该程序采用多个学生姓名,并根据输入的分数计算最终分数。我遇到的问题是,当它循环到第二个学生时,它不允许我进入成绩,我不知道为什么。有什么建议吗C++ 在循环c+;中不断询问用户输入+;,c++,for-loop,while-loop,cout,cin,C++,For Loop,While Loop,Cout,Cin,我正在制作一个程序,该程序采用多个学生姓名,并根据输入的分数计算最终分数。我遇到的问题是,当它循环到第二个学生时,它不允许我进入成绩,我不知道为什么。有什么建议吗 #include <algorithm> #include <iomanip>
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
using std::cin; using std::setprecision;
using std::cout; using std::string;
using std::endl; using std::streamsize;
using std::sort; using std::vector;
int main() {
vector<string> names;
vector<double> finals;
typedef vector<double>::size_type vec_sz;
vec_sz sizeStud;
string name;
double sum, grade;
int counter;
cout<<"Please enter the student's names \"end-of-input\" to end:\t";
while(cin>>name&&name!="end-of-input") {
names.push_back(name);
}
sizeStud = names.size();
if(sizeStud == 0) {
cout<<"No students entered! Please try again."<<endl;
return 1;
}
for(int i = 0; i < sizeStud; i++) {
sum=0;
counter=0;
cout<<"Please enter the grades for "<<names[i]
<<" \"end-of-input\" to end:\t";
while(cin>>grade) {
counter++;
sum+=grade;
}
if(counter==0) {
cout<<"No grades entered! Please try again."<<endl;
}
else {
cout<<endl;
finals.push_back(sum/counter);
}
}
for(int i =0 ; i < sizeStud; i++) {
streamsize prec = cout.precision();
cout<<names[i]<<"'s final:\t\t"<<setprecision(4)
<<finals[i]<<setprecision(prec)<<endl;
}
return 0;
}
样本输出(来自):
您的问题是这一行:
while(cin>>grade)
因为grade
是一个double
,如果您的输入是“输入结束”,while循环将退出,但cin
流将设置为错误状态,并且不会尝试进一步的输入(下一次for
循环迭代将达到while(cin>>grade)
,并立即通过)。您可以使用清除错误状态,并使用(std::numeric_limits::max(),'\n')
使用行的其余输入。然后输入如
fred sally joe end-of-input
10 20 30 any-non-numeric-content
10 20 sally's scores
30 end-of-input
…将“起作用”。使用合适的调试器逐步完成代码的良好起点。是的,使用调试器。提示:虽然(cin>>grade)在操作符周围添加空格是个好主意(它们不会占用可执行文件中的任何空间,并且扩展构建过程的时间可以忽略不计)。注意:有很多接近票数,可能是因为这里没有提到确切的输入。我将编辑一个关于这个问题的插图。。。。
while(cin>>grade)
fred sally joe end-of-input
10 20 30 any-non-numeric-content
10 20 sally's scores
30 end-of-input