I don't fully understand what is wrong with my code, it will read the first lines of any text file but then overloads and keeps displaying "0.00" and then crashes the program. I'm trying to get it to read student's last names and read their GPA scores, and the sentinel value is 99.9, Please help.

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
    //Declare i/o variables
    ifstream inputFile;
    
    //Declare counters
    int counter = 0;
    
    //Declare Arrays
    char dataFile[20] = {""};
    string studentLastName[100] = {""};
    float studentGPA[100] = {0.0, };
    
    
    cout << "Filename: ";
    cin  >> dataFile;
    
    inputFile.open(dataFile);
    
    cout << fixed << setprecision(2) << showpoint;
    
    while(studentGPA[counter] < 99)
    {
                inputFile >> studentLastName[counter];
                inputFile >> studentGPA[counter];
                cout << studentLastName[counter] << endl;
                cout << studentGPA[counter] << endl << endl;
                counter++;
    }
    
    
    
    system("pause");
    return 0;
}

line 18 initializes all array elments to 0. Therefore, line 28 can never find one whose value is anything other than 0. When the loop is first entered, the value of counter is 0 and the value of studentGPA[0] is also 0. The next iteration of the loop the value of counter is 1, so the value of studentGPA[1] is 0.

I think the solution to your program is to use a do loop, not a while loop, so that the test is at the bottom of the loop instead of at the top.

Edited 5 Years Ago by Ancient Dragon: n/a

But I read 99.9 or 100 into the studentGPA array, it should've stopped iterating right? It just keeps giving me 0's. The first line is supposed to be the last name, then the GPA is supposed to be on the next line.

Sit down at your desk and execute your code with paper and pencil. Be careful not to 'fix' the program in your head because you know what it should do. Do exactly what the code tells you to do.

But I read 99.9 or 100 into the studentGPA array, it should've stopped iterating right? It just keeps giving me 0's. The first line is supposed to be the last name, then the GPA is supposed to be on the next line.

No because your logic is backwards, as I previously explained. Your program reads a value, increments the counter then expects to find the value that was just read in the previous slot of the array. You have to check for 99 before incrementing the counter, not after.

No because your logic is backwards, as I previously explained. Your program reads a value, increments the counter then expects to find the value that was just read in the previous slot of the array. You have to check for 99 before incrementing the counter, not after.

Thanks, it worked.

This question has already been answered. Start a new discussion instead.