Trying to create an if/else statement for a string

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    String
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
magnifik
Messages
350
Reaction score
0

Homework Statement


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.

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


i need to now make an if else statement like

if (_________){
count << "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.
 
on Phys.org
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
 
magnifik said:

Homework Statement


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 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
magnifik said:
i need to now make an if else statement like

if (_________){
cout << "You must enter y or n" << endl;
return 1;
}
Something like this:
Code:
if (ch != 'Y' && ch != 'y' && ch != 'N' && ch != 'n')
{
    cout << "You must enter y or n" << endl;
    return 1;
}
magnifik said:
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.

You shouldn't force the user to enter only lower case letters. Any of 'y', 'n', 'Y', or 'N' should be acceptable.
 
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.