简体   繁体   中英

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;
        }
    }
}
if (curID < 0)
{
    return;
}

That's because if you encountered the negative number, your algorithm doesn't store that negative number in studentID[i] .

As a result, studentID still contains uninitialized values from the first invalid position onwards. With no magic marker present, and no counter passed back either, you can't reconstruct the end of the input.

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, ie the return of Read(...) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM