文件无法打开

File wont open.

本文关键字:文件      更新时间:2023-10-16

好吧,我知道这个程序目前有很多问题。我很快就会想明白的。但我主要担心的是为什么我不能打开一个简单的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           Graden";
        cout << "----------------------------------";
        cout << id[counter] << "        " << scores[counter] << "           " <<     grade[counter];
    }
}

infile的声明在哪里?

如果你只是想了解如何阅读文件。你可以试试这个。

void readFile(char filename[])
{
    ifstream infile;
    infile.open (filename);
    if (!infile.good())
        cout << "Can't open file." << endl;    
    string data; 
    while (!infile.eof())
    {
        getline(infile, data);    //read one line of data file content at a time
        cout << data << endl;     //Display file content line by line (for testing)
    }
    infile.close();
}