[英]Bool = true when it should = false in 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 main()內部,我有一個像這樣的函數:
// 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;
}
...
現在的問題。 沒有編譯器問題,但是當我運行代碼時,無論是否將布爾值設置為true或false,每個項目都列在每個房間中。 毫無疑問,解決方案很簡單,但是它堅持讓我難以理解。
您錯誤地使用了分配運算符,它將始終將rustyKeyIn
設置為true並返回true。 所以你應該使用operator ==
if( rooms[currentRoom].rustyKeyIn = true )
應該
if( rooms[currentRoom].rustyKeyIn == true )
// ^^^
或者只是做
if (rooms[currentRoom].rustyKeyIn)
您正在使用=
而不是==
。
當您這樣做時:
if(a = true) {
...
}
如果將a設置為true,然后詢問表達式的結果(a的新值)是否為true(現在為true)。
您想要的是:
if(a == true) {
...
}
或更不那么冗長(更常見):
if(a) {
...
}
使用==
表示相等,使用=
表示賦值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.