-
Strings and IF statement
I am using dev c++ and i want to do something like this but it gives me errors(the error is about the strings and the if statement):
PHP Code:
#include <iostream.h>
int main()
{
cout<<"Guess a word thats about air"<<endl;
char word[] = "oxygen"; //the answer
char input[25]; //users guess
cin>>input;
if (input == word)
{
cout<<"Good Guess you got it right"<<endl;
}
}
-
The error is in the way you are comparing the strings input and word. The == operator can be used to compare only numbers and single characters, not strings. In order to compare two strings you need to use the strcmp or stricmp function, located in string.h.
The prototype is int strcmp(char *,char *);
The function returns a value of 0 if the 2 strings are equal, and a value other than 0 if they are not.
The only difference between strcmp and stricmp is that strcmp takes case into consideration, whereas stricmp does not. Thus...
strcmp("monday","MONDAY") returns a value other than 0, while...
stricmp("monday","MONDAY") returns 0.
-
or use the string class
Code:
#include <iostream.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
cout<<"Guess a word thats about air: "<<endl;
string word = "oxygen"; //the answer
string input; //users guess
cin>>input;
if (input == word)
{
cout<<"Good Guess you got it right"<<endl;
}
system("PAUSE");
return 0;
}
-
-
but make sure you know why it works now and, more importantly, why it didn't work before. Its more important to know that than just to get it working.