2017-05-25 21 views
1

我有以下for loop字符變量,如果語句錯誤C++

string temp; 
int responseInt[10][10] = { {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}}; 

for (int i = 0; i < numberPros; i++) 
{ 
    for (int j = 0; j < numberRes; j++) 
    { 
     cout << "Is " << process[i] << " holding (h), requesting (r), or doing nothing (n) to " << resources[j] << " ?: "; 
     cin >> temp; 
     if (temp == 'n') 
      responseInt[i][j] = 0; 
     else if (temp == 'h') 
      responseInt[i][j] == -1; 
     else if (temp == 'r') 
      responseInt[i][j] == 1; 
    } 
} 

然而,這就像如果if語句將被忽略,因爲對於responseInt的默認值是從來沒有改變過,即使我鍵入hrn

我已經嘗試過使用字符串,但同樣的事情發生。

任何幫助,將不勝感激。

+0

'temp'是一個'string',但''n'',''h''和''r''是'char's。你需要比較喜歡。 –

+2

'=='和'='不是一回事。你從來沒有給'responseInt'的元素賦「0」。 –

+0

@MilesBudnek現在我覺得很愚蠢。半個小時看着我的代碼,特別是if語句,我沒注意到。謝謝,這解決了我的問題! – Jack

回答

0

這工作:

#include <string> 
#include <iostream> 
using namespace std; 

int main(){ 

    string temp; 
    int responseInt[10][10] = { {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}}; 

    int numberPros = 2; 
    int numberRes = 10; 

    for (int i = 0; i < numberPros; i++) 
    { 
     for (int j = 0; j < numberRes; j++) 
     { 
      cout << "Is " << i << " holding (h), requesting (r), or doing nothing (n) to " << j << " ?: "; 
      cin >> temp; 
      if (temp == "n") 
       responseInt[i][j] = 0; 
      else if (temp == "h") 
       responseInt[i][j] == -1; 
      else if (temp == "r") 
       responseInt[i][j] == 1; 
     } 
    } 
} 

cin>>temp正在讀一個字符串,所以最好是用雙引號(例如"r")將其對字符串進行比較,而不是單引號(例如'r')。

請注意,我不得不包括一堆額外的代碼來編譯東西。作爲一個最低工作示例(MWE),這應該是您的問題。