【发布时间】:2021-11-19 06:07:34
【问题描述】:
我正在编写一个从 .csv 文件获取输入的程序。程序运行,但问题是它只返回 .csv 文件的最后一行并跳过所有其他 9 行。 它也不显示平均值和等级。请帮我弄清楚我做错了什么。
教授非常具体地使用了我们迄今为止所学的知识,即循环和函数。我只能使用循环和函数,所以我不能使用数组。
这是 score.csv 文件
#include <iostream>
#include <fstream>
using namespace std;
int testScore1, testScore2, testScore3, testScore4, testScore5;
double avg;
char grade;
double getAvg(int testScore1, int testScore2, int testScore3, int testScore4, int testScore5){
avg = (testScore1 + testScore2 + testScore3 + testScore4 + testScore5)/5;
return avg;
}
char getGrade(double avg){
if (avg >= 90){
grade = 'A';
cout << 'A' << endl;
}else if (avg >= 80){
grade = 'B';
cout << 'B' << endl;
}else if (avg >= 70){
grade = 'C';
cout << 'C' << endl;
}else if (avg >= 60){
grade = 'D';
cout << 'D' << endl;
}else{
grade = 'F';
cout << 'F' << endl;
}
return grade;
}
int main(){
ifstream myFile;
myFile.open("scores.csv");
if(!myFile.is_open()){
cout << "Error" << endl;
}
string testScore1, testScore2, testScore3, testScore4, testScore5;
while (myFile.good()) {
getline(myFile, testScore1, ',');
getline(myFile, testScore2, ',');
getline(myFile, testScore3, ',');
getline(myFile, testScore4, ',');
getline(myFile, testScore5, '\n');
}
cout<< setw(15) <<" Test scores"<<endl;
cout<<"--------------------"<<endl;
cout<< " 1 2 3 4 5 Avg Grade"<<endl;
cout<<"=== === === === === ===== ====="<<endl;
cout<< " "<< testScore1<< " "<< testScore2 << " "<< testScore3 << " "<< testScore4 << " "<< testScore5<< " " << getAvg << " " << getGrade <<endl;
return 0;
}
【问题讨论】:
-
你能走到这一步真是太棒了。我没有看到任何 OCR 代码,甚至没有调用 png 阅读器。
-
@user4581301 我认为图像只是 CSV 文件的图形表示/示例。 CSV 文件实际上会直接包含
77,73,65,55,73等,因此不需要条形码或任何东西。 -
您也没有将字符串转换为整数。 (完整程序示例:onlinegdb.com/uyPXXMy2z)
-
@AnthonyD973 没错。
-
@PKramer 这会让我的工作更轻松,但问题是我仅限于使用函数和循环。我不允许使用任何数组。