c++ - 使用 std::ofstream C++ 的无限 while 循环

标签 c++ arrays while-loop save ofstream

好吧,我有将数组映射保存在 txt 文件中的代码:

std::ofstream output("mapa.txt");
for(int y=0;y<worldHeight;y++) {
    for(int x=0;x<worldWidth;x++) {
        output<<scene[x][y];

        if(x<(worldWidth-1)){output<<",";}
    }
    if(y<(worldHeight-1)){output<<std::endl;}
}

我想把它整合到一个 while 循环中:

std::ofstream output("mapa.txt");

while (true) {
    if (yPos == topOfTheWorld) {
        scene[xPos][yPos] = 2;
    } else if (yPos >= topOfTheWorld) {
        scene[xPos][yPos] = 1;
    } else if(yPos < topOfTheWorld) {
        scene[xPos][yPos] = 0;
    } else {
        scene[xPos][yPos] = 0;
    }

    output<<scene[xPos][yPos] << ",";

    //if(xPos<(worldWidth-1)){output<<",";}

    //if(yPos<(worldHeight-1)){output<<std::endl;}

    yPos++;

    if(yPos>worldHeight) {
        output<<std::endl;
        slope = random(5)-2;
        if(topOfTheWorld<(worldHeight/6)) {
            slope = 1;
        } else if(topOfTheWorld>(worldHeight-10)) {
            slope = -1;
        }
        topOfTheWorld += slope;
        yPos = 0;
        xPos++;
    }

    if (xPos>=worldWidth) {
        break;
    }

}

但由于某种原因,'while' 循环变成了无限...:/

我能做什么?

最佳答案

代码看起来不错。 但是我不确定 scene 是否正确分配。 您有 yPos>worldHeight 和低于 xPos>=worldWidth 这表明您不确定如何比较这些。我怀疑你至少弄错了其中一个。这可以轻松地在场景变量之外写入并覆盖 yPos 或 xPos。

尝试更改为 ypos>=worldHeight 看看是否可行。 如果不检查您为 scene 分配了多少空间,如果它看起来不错,请尝试将其变大一点。

关于c++ - 使用 std::ofstream C++ 的无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942012/

相关文章:

c++ - Qt windeployqt 导致部署不可用

c++ - QTWidgets QTableWidget 因段错误而崩溃

JavaScript:将数组拆分为单个变量

PHP : Array key containing special character not found

java - 将 'While' 循环添加到我的程序中

c++ - 适合初学者的 GTKmm 书籍?我需要在学习 GTKmm 之前学习 GTK+ 吗?

c++ - 可以在两个不同的命名空间中声明同一个实体吗?

python - numpy中不同形状数组之间的乘法

python - python中的无限while循环

java - 我的java程序输出错误