Search code examples
c++arraysinputifstream

Read in Numbers but Stop at Negative C++


What I am trying to do is read in numbers from a text file (currently called "input"). I am creating two arrays, one for an int number and one for a float number. The maximum number of items in the array is set to 50, however the minimum is 1. The identifier for the program to stop reading numbers is any negative number in the int value.

I'm not sure why, but when I read back my array prints out the numbers, skips the final negative number and then prints out gibberish values for the remaining slots (up to 50).

Any advice would be appreciated.

void Read(ifstream &input, int studentID[], float score[])
{
    int curID;
    float curScore;
    for (int i = 0; i < 50; i++)
    {
        input >> curID >> curScore;
        if (curID < 0)
        {
            return;
        }
        else
        {
            studentID[i] = curID;
            score[i] = curScore;
        }
    }
}

Solution

  • Correct your code

    int Read(ifstream & input, int studentID[], float score[])
    {
        int curID, i = 0;
        float curScore;
        while (i < 50) {
            input >> curID >> curScore;
            if (curID < 0)
                break;
            else {
                studentID[i] = curID;
                score[i++] = curScore;
            }
        }
        return i;    // This value will be useful while printing the contents
    }
    

    To avoid gibberish output, only iterate till you read successfully, i.e. the return of Read(...) method.