Question 2: cin doesn't work!

Well, I create the void function, let’s say `Press1`. So I write:

1
2
3
4
5
6
void Press1 ( ) {
int a;
cout << "Please press 1"<< endl;
cin >> a;
if (a==1) {
cout << "congrats, you pressed 1"<< endl;}else{cout << "I said PRESS 1!" << endl;}


Well, so far so good. But now, I want to make the user to be able to cin a again. So I create a while loop:


1
2
3
4
5
6
7
8
9
void Press1 ( ) {
int a;
cout << "Please press 1" << endl;
while (a!=1) 
{
cin >> a;
if (a==1) {
cout << "congrats, you pressed 1" << endl;}else{cout << "I said PRESS 1!" << endl;}
}


Now, the Programm somehow just skips the cin >> a; , so the while loop doesn`t stop. "I said PRESS 1" now gets repeated until my PC busts. The same thing happens if I use a recursion instead of the while loop.

What do I have to change?
try changing the while loop into a do...while loop.
try:
1
2
     cin.clear();
     cin >> a;
both ways, it didn't work. I changed the int into a char. Well, now it's ok, as long you don't type in more than 1 letter.

But there must be a solution!
You're using a before initializing it.

What you did there is equivalent to:
1
2
int a;
while(a!=1) //error line: what's 'a' supposed to be at this point? You just declared it! 


Neither the compiler nor program know. Use a do-while instead.

1
2
3
4
5
6
int a;
do
{
    cin >> a;
    //other code here
}while(a!=1);
Last edited on
Topic archived. No new replies allowed.