【发布时间】:2015-01-11 00:53:39
【问题描述】:
好的,我知道这个程序目前有很多问题。我很快就会弄清楚的。但我主要担心的是为什么我无法打开一个简单的 txt 文件来读取其中的信息。这就是我所拥有的。我需要立即阅读它,但无法弄清楚。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
readStuData(file, students, scores, id, tooMany);
studstruct(id, scores, studnum);
getavg (counter, sum, scores, avg, students);
getgrade(counter, students, scores, avg, grade);
PrintTable(counter, students, id, scores, grade);
}
void readStuData(string file,int& students, int scores[MAX], int id[MAX], bool &tooMany)
{
cout << "Enter the file name: ";
cin >> file;
infile.open(file.c_str());
if (infile.fail()) cout << "Error. Cannot open " << file;
while (!infile.eof())
{
infile >> students;
counter++;
}
students = counter;
tooMany = (students > MAX);
if (tooMany == true) cout << "There are too many students.";
for (counter = 0; counter < students; counter++)
{
infile >> id[counter] >> scores[counter];
}
}
void studstruct(int id[MAX], int scores[MAX], int studnum[MAX])
{
for (counter = 0; counter < students; counter++)
{
struct student;
{
int id[MAX];
int scores[MAX];
int studnum = counter + 1;
}; stu[MAX];
}
}
void getavg(int counter, float sum, int scores[MAX], float avg, int students)
{
for (counter = 0; counter < students; counter++)
{
sum = scores[counter] + sum;
}
avg = sum / students;
}
void getgrade(int counter, int students, int scores[MAX], float avg, char grade[MAX])
{
for (counter = 0; counter < students; counter++)
{
if (scores[counter] <= avg + 10 && scores[counter] >= avg - 10) grade = "Satisfactory";
else if (scores[counter] > avg + 10) grade = "Outstanding";
else if (scores[counter] < avg - 10) grade = "Unsatisfactory";
}
}
void PrintTable(int counter, int students, int id[MAX], int scores[MAX], char grade[MAX])
{
for (counter = 0; counter < students; counter++)
{
cout << "ID Score Grade\n";
cout << "----------------------------------";
cout << id[counter] << " " << scores[counter] << " " << grade[counter];
}
}
【问题讨论】:
-
你输入的是绝对路径还是相对路径?你能在 shell 中 cat 文件吗?
-
检查输入的文件是否存在。还要检查工作目录
-
infile 在哪里声明为 ifstream 对象?
-
@JakeT 如果您需要帮助查找程序中的错误,在示例中引入更多错误通常会适得其反。我们吹毛求疵的人分心了……
-
如果您只发布了与读取文件相关的代码