0

I can't figure out why the output is going through twice.

    int lines = 3
    myReadFile.open("graph.txt");
    if (myReadFile.is_open()) {

        //Read in each value one at a time
        while (!myReadFile.eof()) {
            for(int i = 0; i < lines; i++) {
                for(int j = 0; j<lines; j++) {
                    myReadFile >> output;
                    output2 = atoi(output);
                    Graph[i][j] = output2;
                    cout << "Graph[" << i <<"][" << j <<"] = " << output2 << endl;
                }
            //cout << output << output2 << endl; 
            }
        }

    } else {
        cout << "graph.txt does not exist." << endl; 
    }
    myReadFile.close();

output is below:

Graph[0][0] = 0
Graph[0][1] = 65
Graph[0][2] = 4
Graph[1][0] = 7
Graph[1][1] = 0
Graph[1][2] = 68
Graph[2][0] = 67
Graph[2][1] = 84
Graph[2][2] = 0
Graph[0][0] = 0
Graph[0][1] = 0
Graph[0][2] = 0
Graph[1][0] = 0
Graph[1][1] = 0
Graph[1][2] = 0
Graph[2][0] = 0
Graph[2][1] = 0
Graph[2][2] = 0

It does what I need it to, but it goes back though and zeros them out. Any help would be great! Thanks!

DDukesterman
  • 1,331
  • 5
  • 24
  • 37
  • 5
    [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) Consider the fact that you use the input before checking if it's valid. – chris Nov 26 '13 at 03:33
  • What are you tlaking about? edit: I clicked the link. Looking at it now – DDukesterman Nov 26 '13 at 03:39
  • 1
    The link explains it pretty well, I think. Is there anything specific you don't understand? The point is to make sure your input succeeds *before* using it. – chris Nov 26 '13 at 03:43
  • @DDukesterman and this: `myReadFile >> output` going completely *unchecked* isn't helping much. – WhozCraig Nov 26 '13 at 03:52
  • Thanks! I understand now! Is the up arrow next to the comment the best i can do for you? – DDukesterman Nov 26 '13 at 03:52

1 Answers1

0

efo() returns the eofbit stream state flag, which will be set only when you read past the end of the file. This happens during the second iteration of the while loop where you try to read the file contents into 'output'.

If you put an eof() check after that line, you will be able to accurately break out of all the loops (you would have to use a local flag variable that you can check in all the inner for-loops).

Hari Mahadevan
  • 811
  • 6
  • 13