Question

Why is the nr variable in my code incremented way above 5?

When I test how many times the while loop iterates, it cycles way more times than there are elements in my data file, I cannot understand why.

The data file contains - a 1 2 3 b

Here's my code:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

struct SOMETHING 
{
    string string[10];
    int int_1[100];
};

void main() 
{
    int nr = 0;
    SOMETHING P;
    ifstream D("data.txt");

    while(!D.eof())
    {
        nr++;
        if (nr == 1 || nr % 5 == 0)
        {
            D >> P.string[nr]; 
            cout << P.string[nr] << " ";
        }
        D >> P.int_1[nr];
        cout << P.int_1[nr] << " ";

    }

    D.close();
} 
Was it helpful?

Solution

Examining this:

while(!D.eof())
{
    nr++;
    if (nr == 1 || nr % 5 == 0)
    {
        D >> P.string[nr]; 
        cout << P.string[nr] << " ";
    }
    D >> P.int_1[nr];
    cout << P.int_1[nr] << " ";

}

The reason your nr variable exceeds 5 is that you aren't resetting nr when your after each successful read of each line. I don't know if that's what you want, but the way you've implemented it has a problem (see below):

  • Your structure element clearly has space for 10 elements, but you're only checking and storing the elements at indices 1 and those which are multiples of 5: 0, 1, 5, 10, etc.

  • Using the eof method is bad practice as @P0W has noted in his comment. Use a while loop instead in tandem with std::getline.

OTHER TIPS

The ifstream's internal pointer is not being updated, so the while loop will run indefinitely because eofbit is never set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top