0
我正在制作一个程序,它需要多个学生姓名,并根据输入的成绩计算最终成绩。我遇到的问题是,当它循环到第二个学生时,它不让我进入成绩,我不知道为什么。有什么建议么?用户输入在循环中不断提问C++
#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;
}
示例输入:
fred sally joe end-of-input
10 20 end-of-input
30 end-of-input
样本输出(来自ideone.com here):
Please enter the student's names "end-of-input" to end: Please enter the grades for fred "end-of-input" to end:
Please enter the grades for sally "end-of-input" to end: No grades entered! Please try again.
Please enter the grades for joe "end-of-input" to end: No grades entered! Please try again.
fred's final: 15
sally's final: 1.719e-312
joe's final: 1.316e-312
使用体面的调试器来逐步执行代码的良好起点。 – 2014-12-02 21:54:24
是的,使用调试器。提示:while(cin >> grade) – learningToCode 2014-12-02 21:58:18
在你的运算符周围增加空格将是一个好主意(它们不占用可执行文件中的任何空间,并且延长构建过程的时间可以忽略不计)。 – 2014-12-02 22:03:50