bool choose() {
int answer = 0;
while(answer != 1 || answer != 2) {
cout << endl << "Do you want to encrypt(enter 1) or decrypt(enter 2)?" << endl;
cin >> answer;
}
if(answer == 1) return true;
return false;
}
What is the best way to read from line and compare input with integers?
I know ways cin , gets , getline(cin, answer) .
Which should I use and why?
At the moment, this way is not working, because when i enter 1 or 2, it still stays in while.
This code is a very good candidate for
do-whileloop, and if you use that you’re not required to initialize the variableanswer.And of course, you need to use
&&as others has already pointed out. 🙂By the way, what would happen if user entered any non-integer input such as
hgjkhg?cin>>answerwould fail to read the input and it will remain there forever, and the flag ofcinwill be set failure, andcinwill not be able to read futher input. That means, the loop will never exit!To avoid this, and to make the code more robust and complete you should write it as:
Yes. You can use your
whileloop instead ofdo-while. All that you need to add theif(!(cin>>answer)) { ... }in your code. 🙂