Character input and if comparison

Hello. I'm having a hard time with a C++ problem. I want to input a word (a color) and see a printed message. I used an 'if' to see the printed message and an 'else' see a wrong message in case of a wrong input. Although the compilation shows no errors I'm still getting the wrong message. I could use any help...

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
char col[20];

cout<<"Type your favourite color>";
cin>>col;

if (col=="black") cout<<endl<<"Your choice is black"<<endl<<endl;
else cout<<endl<<"Wrong color!"<<endl<<endl;

system("PAUSE");
return 0;
}


col is a pointer to a char. The important thing there is that it's a pointer. It's not a word. It's a pointer, pointing somewhere in memory. It contains a number. That's all a pointer contains. One number.

"black" is a string literal; it exists somewhere else completely in memory. Using it like this, you actually get a pointer to it. A pointer that contains one number. A number which is the number of some other memory location.

So, you're comparing one number, the number in col, to some other number. Hardly surprising that they're not the same, is it?

If you want to compare two arrays of char, you need to use the strcmp function. You can look it up on this very website.

However, I suggest you start using proper C++ strings, because those have an == operator that works how you're hoping it does. You can look up string on this website too.
if you are using char arrays you need to use strcmp instead of the equality operator:

 
if(strcmp(col, "black") == 0)


if you want to define col as a string instead of a char array then you can use the == operator as you have it.
Problem solved. Thank you very much!
Topic archived. No new replies allowed.