2014-01-11 38 views
0

這可能是我的另一個新手錯誤,但我似乎無法找到一個答案的問題,我想如果我的公共異能幫助別人私下,這可能是最好的。無論如何,自我鞭策,在手頭的問題。Bool = true當它應該= false在C++

在我的文字冒險的頭,我有這樣的結構:

struct roomStruct 
{ 
    // The room the player is currently in, and its interactive objects. 
    string roomName; 
    string size; 
    bool exits[dirnum]; 
    bool rustyKeyIn; 
    bool goldKeyIn; 
     ... 

和實例是這樣的:

void genRooms(roomStruct *rms) 
{ 
    // Generating the rooms of the house, and what items they contain 
    rms[entrance].roomName.assign("the entrance hallway. It's a small room with an exit to the south."); 
    rms[entrance].exits[north] = noexit; 
    rms[entrance].exits[east] = noexit; 
    rms[entrance].exits[south] = livingroom; 
    rms[entrance].exits[west] = noexit; 
    rms[entrance].rustyKeyIn = false; 
    rms[entrance].goldKeyIn = false; 

內部INT主()我有一個functon這樣的:

// Generate the world. 
    roomStruct rooms[roomnum]; 
    genRooms(rooms); 

然後,我有我認爲是問題領域:

// Check for items in the current room. 
    if(rooms[currentRoom].rustyKeyIn = true) 
    { 
     cout << "A rusty key." << endl; 
    } 
    if(rooms[currentRoom].goldKeyIn = true) 
    { 
     cout << "A gold key." << endl; 
    } 
     ... 

現在的問題。沒有編譯器問題,但是當我運行代碼時,無論bool設置爲true還是false,每個房間都會列出每個項目。毫無疑問,解決方案很簡單,但它堅持要躲避我。

+3

您正在使用'='而不是'=='。編譯器通常會提醒你。 –

+0

您應該使用構造函數而不是'genRooms'。 – chris

+0

@Phillip Kinkade礦沒有。 – Trilby

回答

3

您錯誤地使用了賦值運算符,它將始終將rustyKeyIn設置爲true並返回true。 所以,你應該使用比較運算符是operator ==

if(rooms[currentRoom].rustyKeyIn = true) 

應該

if(rooms[currentRoom].rustyKeyIn == true) 
//        ^^^ 

或者只是做

if (rooms[currentRoom].rustyKeyIn) 
+1

或者,甚至更好,如果(房間[currentRoom] .rustyKeyIn){...}'。 – templatetypedef

+0

我是個白癡。即使我應該注意到那一個。謝謝XD – Trilby

+0

別擔心,幾乎每個人都至少做了一次。特別是如果你在C語言和其他使用=的語言之間移動,而不是分配(在這裏考慮VHDL)。 – CrazyCasta

2

您正在使用=代替==

當你這樣做:

if(a = true) { 
    ... 
} 

如果設置一個爲真,然後詢問如果表達式的結果(新價值)是真實的,這就是現在。

你想要的是:

if(a == true) { 
    ... 
} 

還是更簡潔(多見):平等

if(a) { 
    ... 
} 
相關問題