C++ 带有std::of流C++;

C++ 带有std::of流C++;,c++,arrays,while-loop,save,ofstream,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)

我的代码将数组映射保存在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;}
}
std::of流输出(“mapa.txt”);
对于(int y=0;y代码看起来不错。
但是,我不确定是否正确分配了
场景
。 您有
yPos>worldwith
xPos>=worldwith
这表明您不确定如何比较这些值。我怀疑您至少弄错了其中一个值。这很容易在场景变量之外写入并覆盖yPos或xPos

尝试更改为
ypos>=worldHeight
,看看是否有效。
如果没有,请检查为
场景分配了多少空间,如果看起来还可以,请尝试将其增大一点。

如果(xPos>=worldWidth)
循环时中断
,因此显然您需要监视您的
xPos
,重新检查您的算法。使用
std::cout
或调试程序hi P0W!std::cout?我使用的是SFML,而不是控制台..:PWell是解决方案xD,我忘记将>=放入if…正如有人之前所说的那样…因此您的ans是正确的,经过投票和勾选!:D
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;
    }

}