Wayne
Wayne

Reputation: 1

How do I make it so that numbers are being read so I can calculate the average

    cout << "\nName of File name: ";
    cin >> (fileName);
    readFile.open(fileName);    //opens the file

    if (!readFile.is_open()) //if file is open/exists
    {
        cout << "! ! File does not exist ! !" << endl;
        goto Start;
    }
    cout << "\n";
    if (readFile.is_open())
    {
        while (getline(readFile, line)) //read line by line
        {
            cout << line << "\n";
        }
    }
    readFile.close();
    goto Start;

I only have these set of codes to read the text files line by line, and I have a text file that looks like this.

Students    Math    Science    English
Student1    78      87         23
Student2    77      82         95
Student3    86      56         46

How can I see and use the grades so it comes out as integers because I need to use them for calculations?

Upvotes: 0

Views: 48

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122820

Define a structure for students:

struct Student {
    std::string name;
    int math;
    int science;
    int english;
};

Provide a input operator:

std::istream& operator>>(std::istream& in, Student& st) {
    in >> st.name >> st.math >> st.science >> st.english;
    return in;
}

And use it to store students data in a vector:

std::vector<Student> students;
// ... open file etc. ...
Student st;
while(readFile >> st) students.push_back(st);

Note that I assumed that the names do not contain whitespace characters.

Upvotes: 2

Related Questions