Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Trying to create an if/else statement for a string

  1. Apr 8, 2010 #1
    1. The problem statement, all variables and given/known data
    I need to make an error message that says "You must enter y or n" for a program. Right now I have this... this is only the part that i need help with, not the whole code.

    cout << "Student? (y/n): ";
    string student;
    getline(cin, student);


    i need to now make an if else statement like

    if (_________){
    cout << "You must enter y or n" << endl;
    return 1;
    }

    i'm not sure what to put in the blank. i could do student.empty(), but the error message would only show up if a user didn't input anything. i need to put something in the if function that would cause the error message to show if the user didn't put anything, wrote a capital Y or capital N, wrote some other letter, etc.
     
  2. jcsd
  3. Apr 9, 2010 #2
    hi,
    try
    if ((not equal to y) or (not equal to x) or (not equal to Y) or (not equal to X))

    which will return true if the answer is not any of x, y, X, Y

    hope this helps
     
  4. Apr 9, 2010 #3

    Mark44

    Staff: Mentor

    I would use a char variable, not named student. A name like student is misleading, since a casual reader of the code would think it represented some attribute of a student, rather than a single character.

    I would use getchar() to get the character
    Something like this:
    Code (Text):
    if (ch != 'Y' && ch != 'y' && ch != 'N' && ch != 'n')
    {
        cout << "You must enter y or n" << endl;
        return 1;
    }
    You shouldn't force the user to enter only lower case letters. Any of 'y', 'n', 'Y', or 'N' should be acceptable.
     
  5. Apr 11, 2010 #4
    I agree with Mark44,

    You can have the 4 conditions in your if statement or you can convert the character the user enters to upper case (or to lower case). But that isn't necessary, it just makes the runtime shorter.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook