"while" problem

hello , i have a some problem , if i write yes or no programme working succesfull but if i dont write yes or no i mean if i write anything else programme say "please write yes or no" yes i want to do that but if i will write again yes or no programme say again "please write yes or no"

Hey ! Welcome our programme
Do you want to register = asdasd
please write yes or no = yes
please write yes or no = no
please write yes or no = no
please write yes or no = yes
please write yes or no = asd
please write yes or no = asdasdasd




#include <iostream>

using namespace std;

int main()
{
cout << "Hey ! Welcome our programme";
string ans;
cout << endl << "Do you want to register";
cin >> ans;
if(ans=="yes")
{
cout << "please write your username";
string username;
cin >> username;
cout << "welcome " << username << " !";

return 0;
}
else if(ans=="no")
{
cout << "thanks for visiting us";

return 0;
}
while(ans!="yes" || ans != "no")
{
cout << "please write yes or no";
cin >> ans;
}
}
please use [ code ] tags in the future. you're also missing #include <string> .

your while loop is wrong. Lets say the input is "yes", the test is:

"yes" != "yes" || "yes" != "no"

The first condition is false, but the second one (yes != no) is true, so the loop continues. You need this to be &&, then the test becomes:

"yes" != "yes" && "yes" != "no"

yes != yes, so it stops the loop. https://en.wikipedia.org/wiki/Short-circuit_evaluation
Last edited on
You should have only one return 0; in your program, and it should be at the end of your main function. Otherwise you're exiting the program within all your if statements..
It's perfectly fine to have multiple return 0;. In fact, it is common during the program driver's startup phase to exit early if you receive invalid input, the user send a command to stop early (like "no" in this case), or a required resource couldn't be acquired.

edit:
in fact, i do it in my projects:
https://gitlab.com/ntchambers/spellcheck/blob/master/src/spellcheck.c#L20-24
https://gitlab.com/ntchambers/rpn/blob/master/rpn.c#L59-113 // ignore the bad rpn implementation
https://gitlab.com/ntchambers/toybin/blob/master/c/dice.c
Last edited on
To be pedantic I would return 1 or 2 in the case of failure :P
It can actual matter if you rely on the return values for scripts.
But yeah, not a big deal.
Last edited on
Right, I was more referring to the act of returning than the value. 0 should be used for successful exits (which appears to be the case here) and > 0 for errors.
Topic archived. No new replies allowed.