-
selection problem
Hello guys, i have this small problem. when i run this code and select 1(new user) it should just print out Testing 1 only but it print out another Invalid Selection. What is the problem here??
Lot of help, Thanks
Coding
Code:
int main()
{
int select = 0;
while (select != 51)
{
printf("1. New User\n");
printf("2. Existing User\n");
printf("3. Exit\n");
printf("Please Enter Selection [ 1-3 ] : ");
select = getchar();
switch (select)
{
case 49: printf("Testing 1\n");
break;
case 50: printf("Testing 2\n");
break;
case 51: printf("Good Bye\n");
break;
default: printf("Invalid Selection\n");
break;
}
}
}
Result
Please Enter Selection [ 1-3 ] : 1
Testing 1
1. New User
2. Existing User
3. Exit
Please Enter Selection [ 1-3 ] : Invalid Selection
1. New User
2. Existing User
3. Exit
Please Enter Selection [ 1-3 ] : 2
Testing 2
1. New User
2. Existing User
3. Exit
Please Enter Selection [ 1-3 ] : Invalid Selection
1. New User
2. Existing User
3. Exit
Please Enter Selection [ 1-3 ] : 3
Good Bye
-
This is where knowing how things happen under the hood, so to speak, help with understanding how to write proper code.
Let's take a look at what you're doing:
The program first prompts you for a value. The input buffer is empty. You didn't enter anything, yet, so it asks you for a value. You enter '1' and then press Enter. Here's what the input buffer looks like now:
getchar() grabs the first char you typed, which is the '1', and that's why it prints "Testing 1". Now it loops and it tries to read another selection. The input buffer looks like this:
So getchar() doesn't ask you for another character. It's already got one in the buffer. So it selects the '\n'.
This is why you have "Invalid Selection", because it's reading the '\n' as your input.
You repeat the same things with 2 and 3 later on.
A hackish solution is to just perform a double getchar(). The problem with that is if you have a dumb user that wishes to type a book. Consider if the user enters this:
Code:
"It was the best of times and the worst of times..."
The buffer starts out looking like this:
Code:
'I', t', ' ', 'w', 'a', 's'....
This is obviously going to cycle for awhile telling the user they entered invalid entries.
So what you could do is have an extra int called c. Call getchar() to read the user's first value like you normally do, and then run this line:
Code:
while(((c = getchar()) != '\n') && (c != EOF));
This will keep reading from the input buffer until either '\n' or EOF is reached and get the input lined up for the next entry.
-
getchar() reads a single char. First, it reads a '1', and your program processes it. On the next iteration, it sees the '\n' (newline) that you typed after the 1.
scanf() might serve you better here, or you'll need to wrap getchar() with something so more intelligence.
Also, instead of case 49, use case '1' - just incase '1' != 49, and it self-documents to boot.
-