I would have thought that if I entered the word hello it would output HI!!!!! bit it does'nt. What's wrong with it?Code:#include <iostream.h> char foo[10]; int main() { cin >> foo; if (foo == "hello") { cout << "HI!!!!!"; } return 0; }
I would have thought that if I entered the word hello it would output HI!!!!! bit it does'nt. What's wrong with it?Code:#include <iostream.h> char foo[10]; int main() { cin >> foo; if (foo == "hello") { cout << "HI!!!!!"; } return 0; }
Use strcmp to compare 2 strings.
Thanks for the reply but I'm still not sure what's wrong with the code posted above.
The name of the character array is the same as a pointer to the first element of the array, so here you are comparing:
if(h == "HELLO")
To which it is saying, false (1).
Or maybe even it's an address such as:
if(343433 == "hello")
I'm not sure that is the case bacuase if i tell it to output the foo variable, it will output what i entered rather than just one byte as you are suggesting.The name of the character array is the same as a pointer to the first element of the array, so here you are comparing:
if(h == "HELLO")
To which it is saying, false (1).
Try this:
Code:if (strcmp(foo, "hello") == 0) { cout << "HI!!!!!"; }
Yes, but is'nt there a way to do it without using a function?
The name of the array is a pointer to the first element:
char name[222];
name is the same as &name[i]
Check out your textbook, the chapter on arrays.
The only way to get around it is to create a new type. In C++ they have a string type, that allows you to make the comparison that you want to make, because it overloads the = operator.
When you are outputting the array, you are using printf which takes a pointer to char arguement, or in other words the name of the array (which is a pointer to the first element).
Originally posted by Unregistered
Yes, but is'nt there a way to do it without using a function?Code:int main() { int i = 0; char foo[10]; char s[] = "Hello"; cin >> foo; while(s[i] == foo[i] && s[i]) i++; if(!s[i] && !foo[i]) { cout << "HI!!!!!"; } return 0; }