- #1
yungman
- 5,755
- 293
For the lack of better description. cin, cin.get() are used to input char. It is all good if you don't make mistake hitting say the Enter key of Tap key etc.
For example in this program, if I hit Enter instead of an alphabet for choice, it will mess up. more importantly at the end of the while loop, if I accidentally hit the Enter key for more in line 20, it will exit the program instead of cycling back to the start of the program. I lost all the data I keyed in. Using cin >> choice made it much better, BUT then the stream operator create another set of problem for the next cin.getline(). It will not work for my program.
Yes, I know, type more carefully! But $hit do happens. I just want to know whether there is an easy to fix this.
Thanks
C++:
//switch-case
#include <iostream>
using namespace std;
int main()
{
char choice, more;
do
{ cout << " Enter either a, r, s, d or q: ";
cin.get(choice);
cin.ignore();
switch (choice)
{ case 'a': cout << " you chose a."; break;
case 'r': cout << " you chose r."; break;
case 's': cout << " you chose s."; break;
case 'd': cout << " you chose d."; break;
case 'q': cout << " you chose q."; break;
default: cout << " Not a choice.";
}
cout << "\n\n Want to do it again? ";
cin.get(more);
cout << endl;
} while (more == tolower('y'));
}
For example in this program, if I hit Enter instead of an alphabet for choice, it will mess up. more importantly at the end of the while loop, if I accidentally hit the Enter key for more in line 20, it will exit the program instead of cycling back to the start of the program. I lost all the data I keyed in. Using cin >> choice made it much better, BUT then the stream operator create another set of problem for the next cin.getline(). It will not work for my program.
Yes, I know, type more carefully! But $hit do happens. I just want to know whether there is an easy to fix this.
Thanks