If....else

Can anybody help a full-on newb figure out why this program outputs <bad> no matter what is input. It should output <good> if <B> is input, correct? And <bad> if anything else is input.




#include <iostream>
using namespace std;
char doc;
char B;
char good;
int main()
{
cout << "enter number" << endl;
cin >> doc;
if (doc = B)
cout << "good" << endl;
else
cout << "bad" << endl;

system("PAUSE");
}
1. You are not assigning a value to the char variable 'B', meaning it contains garbage, meaning you have a 1 in 256 chance to actually get a match.
2. Your if uses the assignment operator. Comparing requires two equals signs.
3. Your code should actually be returning "good" all the time, unless by mere chance you end up with a value of zero in B.
4. Please use code tags to show code. Please put code tags around your code so it is presentable.
You don't need to declare one more variable B .
Just try modifying your if condition:

if(doc == 'B')
Last edited on
I turned the operator into a comparison and added single quotations, now it works. This was part of a larger program I was writing but after 20 straight hours I was too loopy to catch even the obvious. I knew it was going to be something simple. Thank you. My Professor moves through the information so quickly that the details get lost. Its only week two and we're into recursive pi functions. I'll figure out how to use code tags now. Again, thanks.
Topic archived. No new replies allowed.