char variable and if statement error C++
An answer to this question on Stack Overflow.
Question
I have the following for loop:
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;
}
}
However, it's like if the if statements are ignored, since the default values for responseIntare never changed, even if I type h or r or n.
I already tried with strings, but the same thing happens.
Any help would be appreciated.
Answer
This works:
#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;
}
}
}
Your cin>>temp is reading a string, so it is best to compare it against strings by using double quotes (e.g. "r") rather than single quotes (e.g. 'r').
Note that I've had to include a bunch of extra code to make things compile. This should have been in your question, as a minimum working example (MWE).