Case code showing more than once

I was wondering why does my Switch code part shows "Incorrect value. Please try again.\n" several times if I enter something like "yyyy". If I enter 5 letters or numbers, it will display the message 5 times.


#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

void main()
{
int x,y;
char a;
LAS1:
cout << "Enter a number: ";
cin >> x;
y=x%2;
if (y==0)
{
cout << "\nThe number is even.\n\n\n";
LAS2:
cout << "Continue?[Y\N] ";
cin >> a;
switch (a)
{
case 'Y':
case 'y':
goto LAS1;
case 'n':
case 'N':
break;
default:
cout << "Incorrect value. Please try again.\n";
goto LAS2;
}
}
else
{
cout << "\nThe number is odd.\n\n\n";
}
getch();
}
Last edited on
Firstly, this is horrible code (and is not C++ - if your compiler is happy with this, get a new compiler that is C++ compliant). The use of goto in this way throws away the whole point of functions and makes your code difficult to follow and correspondingly hard to maintain and prone to bugs. Better that someone tells you these things now.

I see that you read in to a which is a single character. I suspect that when you put 5 characters into the input buffer, only one of them is used, and next time the code comes around to reading in a single character to a, the next one is read, leaving three in the buffer, and so on.

If you use C++ strings, you won't have this problem. They're well worth looking into.
Last edited on
Topic archived. No new replies allowed.