将char转换为字符串不能正常工作C ++

时间:2013-09-20 20:21:17

标签: c++ arrays char sfml

我有那段代码:

for (int x = 0; x<(worldWidth-1); x++) {
    for (int y = 0; y<(worldHeight-1); y++) {
        sf::Texture texture;
        if (!texture.loadFromFile("images/blocks/" + ruta(mapa[y][x]) + ".png"))
        return -1;

        sf::RectangleShape rectCaja(sf::Vector2f(16, 16));
        rectCaja.setPosition(sf::Vector2f(x*16, y*16));
        rectCaja.setTexture(&texture);
        window.draw(rectCaja);
    }
}

打印盒子(16 * 16像素),即游戏中的“块”问题是它不打印任何块,它直接崩溃我不知道为什么:/

我知道(通过控制台测试)数组“mapa”没有错...所以我唯一的解释是ruta函数不能正常工作......(我用std测试过它: :string var =“dirt”;它工作正常)...:/

std::string ruta(char id) {

if (id=='0') return "air";
if (id=='1') return "stone";
if (id=='2') return "dirt";
if (id=='3') return "grass_side";
if (id=='4') return "coal_ore";

}

如果有人想要保留代码,则有:http://pastebin.com/5jvbzwkR

谢谢! :P

3 个答案:

答案 0 :(得分:1)

只是猜测,因为没有足够的信息可以肯定,但这可能就是答案

std::string ruta(int id) {

if (id==0) return "air";
if (id==1) return "stone";
if (id==2) return "dirt";
if (id==3) return "grass_side";
if (id==4) return "coal_ore";

}

在C ++中,你必须小心 types ,并理解例如intchar之间的区别。值为“3”的char与值为3的int不同。

答案 1 :(得分:1)

我立即看到的一个问题是,您要将intchar进行比较。考虑:

std::string ruta(int id)
{
    switch( id )
    {
    case 0:
        return "air";
    case 1:
        return "stone";
    case 2:
        return "dirt";
    case 3:
        return "grass_side";
    case 4:
        return "coal_ore";
    }
}

答案 2 :(得分:1)

这是您的场景声明:

int scene[worldWidth][worldHeight]; 

以下是填写场景的方法:

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

    //etc...
}

以下是您写入mapa.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;}
}

基本上这意味着你要将数值0和1写入mapa.txt而不是字符值'0'和'1'。然而在你的ruta函数中,你要比较'0'和'1'。您应该在没有单引号(')的情况下与0和1进行比较。

相关问题