为什么这个印两次

Why does this print twice?

本文关键字:两次 为什么      更新时间:2023-10-16

我不明白为什么输出要经过两次。

    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();

输出如下:

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

它做了我需要它做的事,但它会返回并将它们清零。任何帮助都会很棒!谢谢

efo()返回eofbit流状态标志,只有在读取超过文件末尾时才会设置该标志。这种情况发生在while循环的第二次迭代中,您试图将文件内容读取到"output"中。

如果在该行之后进行eof()检查,您将能够准确地断开所有循环(您必须使用一个本地标志变量,您可以在所有内部for循环中进行检查)。