我正在编写 C++ 代码,它允许我使用数组从文件中输入数据。到目前为止它运行良好,但我在输入多个数据条目时遇到问题。只显示第一个数据条目,其余的不显示。
在文件中
报告.txt
Amy Jackson
3 3 5
Robert Thomas
2 2 5
Belicio Juarez
5 5 4
基本上它的书写方式是任何超过 5 分或低于 0 分的都被淘汰,除了 3 个条目之外的任何东西都被淘汰。它适用于第一个条目,但不适用于其余条目。我正在考虑使用一个函数来执行此操作,但不确定如何去做。会很感激一些帮助
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const string report = "report.txt";
const int J_PANEL = 3;
const int ATHELETES = 1;
ifstream inFile;
inFile.open(report);
if (!inFile) {
cout << "report cant be opened " << report << endl;
return 0;
}
string atheletes[ATHELETES];
double panel[J_PANEL];
bool error = false;
double sum = 0;
int entries = 0;
if (!getline(inFile, atheletes[0])) {
error = true;
}
for (int i = 0; i < J_PANEL; i++) {
if (!(inFile >> panel[i])) {
error = true;
break;
}
if (panel[i] < 0 || panel[i] > 10) {
error = true;
break;
}
sum += panel[i];
entries++;
}
if (error || entries != 3) {
cout << "wrong scores\n" << endl;
cout << atheletes[0] << " is eliminated" << endl;
} else {
double avg = sum / J_PANEL;
cout << atheletes[0] << "'s results: ";
for (int i = 0; i < J_PANEL; i++) {
cout << " " << panel[i];
}
cout << endl;
cout << "the average is " << avg << endl;
}
return 0;
}
**输出:**
Amy Jackson's results: 3 3 5
the average is 3.66667
期望的输出:
Amy Jackson's results: 3 3 5
the average is 3.66667
Robert Thomas's results: 2 2 5
the average is 3
Belicio Juarez's results: 5 5 4
the average is 4.66667