档案不会打开。

时间:2014-11-13 18:55:48

标签: c++ file file-io

好的,所以我知道这个程序目前有很多问题。我很快就会搞清楚。但我主要担心的是为什么我无法打开一个简单的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];
    }
}

1 个答案:

答案 0 :(得分:1)

您对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();
}