Question

Well I have that code that saves an array map on a txt file:

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;}
}

I want to integrate it to a while loop:

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;
    }

}

But for some reason the 'while' loop becomes infinite... :/

What can I do?

Was it helpful?

Solution

The code looks good. However I'm not sure if scene is correctly allocated. You have yPos>worldHeight and below xPos>=worldWidth which suggests that you're not sure how to compare these. I suspect you got at least one of them wrong. This can easily write outside the scene variable and overwrite yPos or xPos.

Try changing to ypos>=worldHeight and see if that works. If not check how much space you allocate for scene and if it looks OK try making it a bit bigger.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top