Lucia
Lucia

Reputation: 13587

C++ weird ifstream reassign value error

I'm learning C++ and ran into a very weird error: I don't understand why the candidateNum changes after the first for loop.

int main()
{
    int candidateNum;
    int votesArr[] = {};
    string namesArr[] = {};
    ifstream inputStream;

    inputStream.open("votedata.txt");
    inputStream >> candidateNum;

    for (int i = 0; i < 5; i++) {
        inputStream >> namesArr[i];
        inputStream >> votesArr[i];

        cout << i << ", candidateNum: " << candidateNum << endl;
    }

    inputStream.close();
    return 0;
}

This is the votedata.txt:

5
Johnson 5000
Miller 4000
Duffy 6000
Robinson 2500
Ashtony 1800

Weird thing is, the output was:

0, candidateNum: 5
1, candidateNum: 4000
2, candidateNum: 4000
3, candidateNum: 4000
4, candidateNum: 4000

How come candidateNum changed at all? I tested and found that deleting either of the inputStream >> xArr[i] line would "fix" the error. How can this be? Where did candidateNum get reassigned?

Upvotes: 0

Views: 71

Answers (1)

rodrigo
rodrigo

Reputation: 98486

In C++ arrays are fixed size so:

int votesArr[] = {};

that is equivalent to:

int votesArr[0];

declares an array of 0 elements, and that size will not change during the time of that variable (and the same for the other array).

So when you do:

inputStream >> votesArr[i];

you are writing outside the bounds of the array, and trigger undefined behavior, probably overwriting memory of other variables and causing all sorts of unpredictable effect.

My recommendation is to switch from old-style arrays to std::vector:

#include <vector>
std::vector<int> votesArr(5);
...
votesArr.resize(candidateNum);

I don't know exactly what you want to do with the array, but you can give the size at creation time (empty by default) and you can resize it at any time.

Upvotes: 2

Related Questions