Strings and IF statement

This is a discussion on Strings and IF statement within the C++ Programming forums, part of the General Programming Boards category; I am using dev c++ and i want to do something like this but it gives me errors(the error is ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    14

    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;
    }



  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    79
    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.

  3. #3
    Unregistered
    Guest
    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;
    }

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    14
    Thanks it worked

  5. #5
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    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.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21