簡體   English   中英

將char轉換為字符串不能正常工作C ++

[英]Convert char to string doesn't work fine C++

好吧,我有那個代碼:

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

只是一個猜測,因為沒有足夠的信息可以確定,但這可能是答案

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 ++中,您必須注意類型 ,並了解intchar之間的區別。 值為'3'的char與值為3的int不同。

我立即看到的一個問題是,您正在將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";
    }
}

這是您的場景聲明:

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進行比較,並且不要使用單引號(')。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM