Thread: If and char

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    545

    If and char

    Another rookie question from Bumfluff:

    Is it possible to use characters in if statemnets? ie if myvariable == Y etc.

    Thanks

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Yep. But, a character literal is written: 'Y'. Note the single quotes.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    545
    Ok, single quotes, got it. At first I thought you said not the single quotes but that would be as I just typed it. Is it possible to use a word or sentence?

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Use double quotes for strings, which hold 0 or more characters. You should be using the C++ string class for your string variables. If you are, then you can use == like you do with char variables.

    If you use C style strings, which are just character arrays with a null character to indicate the end of the string, then you cannot use ==, you have to use a function like strcmp to compare the strings.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    545
    I tried a string in my programme but it doesnt work properly:
    Code:
    #include <iostream>
    #include <string>
    #include <stdlib.h>
    
    using namespace std;
    
    int main()
    {
     string Question = "";
     string LoopStop = "";
     do
     {
     cout<<"Please Ask The Computer A Question:"<<endl;
     getline(cin,Question);
     cout<<endl;
     cout<<"NO!"<<endl;
     cout<<" \n"<<flush;
     cout<<"Would you like to continue? (yes / no *note lower case)"<<endl;
     getline(cin,Question);
     cin.ignore();
     cout<<" \n"<<flush;
     system ("CLS");
     }
     while ( LoopStop == "yes" );
     return 0;
    }

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    What doesn't work? You should give that kind of information so we can help better.

    I did notice that your second call to getline reads into Question, when you probably meant LoopStop. Also, I'm not sure that the cin.ignore() is necessary there (you might want it outside the loop).

    edit - I just noticed your other thread. The cin.ignore() was required there because you used cin >>. It is not required after getline because getline automatically ignores the newline character at the end of the user input from when the user hits enter.
    Last edited by Daved; 11-07-2005 at 12:28 PM.

  7. #7
    Registered User
    Join Date
    Nov 2005
    Posts
    545
    Stupid me! The getline Question was a stupid mistake and thanks for the advice.

    God I have learned a lot in the two days since I joined this forum.

Popular pages Recent additions subscribe to a feed