Thread: Using if statments to compare characters

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    49

    Using if statments to compare characters

    I wanted to know if it is possible to use if statements to compare characters. For example, suppose I wanted to write a program to respond differently to different char inputs. I can't seem to do this using if statemtents. Here is a sample code.

    Code:
    #include <iostream>
    using namespace std;
    
    
    int main(){
        char x;
        cout << "Enter a character\n";
        cin >> x;
        cin.ignore();
        
        if (x == y){
              cout << "You entered Y.\n";
              }
        if (x != y ){
              cout << "You didn't enter Y.\n";
              }
              
        cin.get();
        return 0;
    }
    When I compile this it results in an error that says it is the first time the char y is declared. So my question is, how do I compare char inputs using if statments? Is there another way to do this? Yes, I'm new to this...

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    You did not declare a variable y.
    if you want to compare with the literal y use:
    Code:
    if ( x == 'y' )
    Kurt

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    49
    Thanks Zuk, that's just what I needed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with compare two characters
    By Martin Kovac in forum C Programming
    Replies: 1
    Last Post: 04-09-2009, 12:45 PM
  2. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  3. Replies: 7
    Last Post: 05-11-2008, 10:57 AM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Why can't i compare characters like this?
    By Nutshell in forum C Programming
    Replies: 6
    Last Post: 04-24-2002, 07:46 AM