0

I am trying to write a code to read values from a csv file and store them in four separate arrays. Each row has 4 values. The first value will be stored in one array the second in another, the third in another, and the fourth in another. This is the code I have written so far:

while (FBWS.good())
{
    getline ( FBWS, infor,',');
    istringstream (infor) >> infoc;
    FBWSmin[i]=infoc;

    cout << FBWSmin[i-1] << " ";
    cout << FBWSmin[i] << "\n";

    getline ( FBWS, infor,',');
    istringstream (infor) >> infoc;
    FBWSplus[i]=infoc;

    getline ( FBWS, infor,',');
    istringstream (infor) >> infoc;
    FBWStax[i]=infoc;

    getline ( FBWS, infor,',');
    istringstream (infor) >> infoc;
    FBWSmax[0]=infoc;

    i=i++;

}

The value is stored in the array after one loop but after the next loop runs, the previous stored value resets to zero. I can't determine if its coding syntax or what.

  • __1)__ Is `FBWSmax[0]=infoc;` supposed to be `FBWSmax[i]=infoc;`? __2)__ Your `while (FBWS.good())` input loop is [going to be a problem](http://stackoverflow.com/questions/4324441/testing-stream-good-or-stream-eof-reads-last-line-twice). – Blastfurnace Jul 26 '13 at 18:31

3 Answers3

1

In short, i=i++ does not update i. i++ increments the value, and returns the previous value.

This version is undefined behaviour anyway, as you update the value twice in one expression. However, what is probably happening in practice is you are just setting i back to itself every time, and overwriting the same row on every iteration. However, undefined behaviour means anything could happen! Your entire program becomes nonsensical.

Just write ++i; to increment i.

(BTW, the other answers mention sequence points. I didn't bother because they are a fairly technical concept that you generally shouldn't be thinking about while writing code anyway: just write the clearer version. Also, they don't exist any more, the new version of The Standard talks about "sequenced before" and "sequenced after".)

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
1

Your increment is not correct:

i = i++ ;

even worse it is undefined behavior, which means that the program can exhibit any behavior even behavior that appears correct but you can not predict the result. It is undefined in this case because you are not allowed to modify the same variable more than once between sequence points. Just use standalone pre(++i) or post(i++) increment, for example:

++i ;

Also using good or eof is not going to work.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

If you want to increment a variable, it should be either:

i++;

or

i = i + 1;

Putting the two together, as

i = i++;

results in undefined behavior -- trying to update the same variable twice between two sequence points is not specified.

Barmar
  • 741,623
  • 53
  • 500
  • 612