Thread: Getch() and IF problem...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    7

    Getch() and IF problem...

    Ok, he's the problem...

    #include iostream.h
    #include conio.h

    int main()
    {

    char movement;

    movement = getch();

    cout << movement;

    if(movement == 8)
    {
    cout << "This is what happends when you press 8";
    }

    return 0;
    }

    So, it should print "This is what happends when you press 8", but it doesn't. I have no idea what it could be, because it looks as right as rain. Anyways, thanks for the help!

    Mike

  2. #2
    Registered User Strider's Avatar
    Join Date
    Aug 2001
    Posts
    149
    If you input as char then look for a char:
    Code:
    #include <iostream.h>
    #include <conio.h>
    
    int main() 
    { 
    
    char movement; 
    
    movement = getch(); 
    
    cout << movement; 
    
    if(movement == '8') 
    { 
    cout << "This is what happends when you press 8"; 
    } 
    
    return 0; 
    }
    David
    One Ring to rule them all, One Ring to find them,
    One Ring to bring them all and in the darkness bind them
    In the Land of Mordor where the Shadows lie.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    within the code you write 8 is a numerical value, '8' is a char, "8" is a string although all appear as 8 on the screen. You have to indicate which type of variable you are refering to within the code.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    7

    Lightbulb AH-HA!

    OK, It works now with much help from Perderabo from the unix.com forum. What was wrong was the loop itself:

    if(movement == 8)

    If you are to set the variable 'movement' to an 'int' instead of a 'char', what you see when 'cout << movement;' is 56. This is the ANSII of 8. So when you tell 'if(movement == 8)', it actually is looking for 56. That is when you turn movement back into a char and then:

    if(movement == '8')

    And there, it works just fine...gee, those 2 little ' make a hell of a lot of difference, huh? ...phew!

    Mike

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    7

    Talking Opps

    Sorry Strider, i didn't see that you fixxed it before. Thanks for your help, though, I appreciate it!

    Mike

  6. #6
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    if(movement == 8)

    If you are to set the variable 'movement' to an 'int' instead of a 'char', what you see when 'cout << movement;' is 56. This is the ANSII of 8. So when you tell 'if(movement == 8)', it actually is looking for 56. That is when you turn movement back into a char and then:

    if(movement == '8')
    Actually, if you have it the way you did, wouldn't it look for movement == backspace (which has an ASCII value of 8)?

Popular pages Recent additions subscribe to a feed