【问题标题】:Why does this print twice?为什么会打印两次?
【发布时间】:2013-11-26 03:32:33
【问题描述】:

我无法弄清楚为什么输出会经历两次。

    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

它可以满足我的需要,但它会返回并将它们归零。任何帮助都会很棒! 谢谢!

【问题讨论】:

  • while (!eof()) is wrong. 在检查输入是否有效之前,请考虑一下这样一个事实。
  • 你在说什么?编辑:我点击了链接。现在看看
  • 链接解释得很好,我认为。有什么具体的你不明白吗?关键是要确保您的输入在使用之前成功。
  • @DDukesterman 和这个:myReadFile &gt;&gt; output 完全不检查并没有多大帮助。
  • 谢谢!我现在知道了!评论旁边的向上箭头是我能为您做的最好的吗?

标签: c++ for-loop cout


【解决方案1】:

efo() 返回 eofbit 流状态标志,仅当您读取文件末尾时才会设置该标志。这发生在您尝试将文件内容读入“输出”的 while 循环的第二次迭代中。

如果您在该行之后放置一个 eof() 检查,您将能够准确地跳出所有循环(您必须使用可以检查所有内部 for 循环的局部标志变量)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多