1 Replies - 22394 Views - Last Post: 27 October 2012 - 12:07 PM Rate Topic: -----

#1 ZacCarlson   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 146
  • Joined: 08-October 12

Trying to write a while loop for a yes or no answer (c++)

Posted 27 October 2012 - 11:46 AM

I'm trying to write a while loop for if the user does not enter y, Y, n, or N they are prompted an error message and asked to enter the proper letter in order to continue. I've searched for solutions and all I can find is the strcmp command. Is this the only solution? If so, I'm having trouble understanding how to use that command. Can somebody explain it please and give me an example using a similar code to what I have. I know the "!=" is wrong but I'm showing you what I'm trying to do:

 #include<iostream>
 #include<time.h>
 #include<stdio.h>

 using namespace std;

 int main(){
    char answer;

    cout << "Do you want to continue (Y or N)" << endl;
    cin >> answer;
    while ( answer !== 'Y'|| answer != 'N' || answer != 'n' || answer != 'y'){
       cout << "Wrong! Enter a Y, y, N, or n: " << endl;
       cin >> answer;
    }

 return 0;
 }




Is This A Good Question/Topic? 0
  • +

Replies To: Trying to write a while loop for a yes or no answer (c++)

#2 jimblumberg   User is online

  • member icon

Reputation: 5765
  • View blog
  • Posts: 17,654
  • Joined: 25-December 09

Re: Trying to write a while loop for a yes or no answer (c++)

Posted 27 October 2012 - 12:07 PM

Quote

I've searched for solutions and all I can find is the strcmp command. Is this the only solution? If so, I'm having trouble understanding how to use that command.

No using strcmp() is actually not a solution. You are using a single character so testing the character is correct. The strcmp() function only works when comparing C-strings (zero terminated Character arrays).

Quote

Can somebody explain it please and give me an example using a similar code to what I have. I know the "!=" is wrong

Actually using the "!=" is correct. What you have wrong is that you are using the wrong logical operator. You should be using the logical and (&&) not the logical or. Because you want to skip this loop if your entry is not y and is also not Y and also not n and also not N.

You also have a typo in the first comparison, you have an extra '='.

Jim

This post has been edited by jimblumberg: 27 October 2012 - 12:08 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1