getchar - multiple input problems
Hi,
I've run into a silly problem that I thought I'd ask for some help with:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i;//Global input var
//Example Menu
int main()
{
printf("1) Save File \n");
printf("2) Go Deeper \n");
printf("3) Exit \n");
userInput();
while (i < 1 || i > 3) //Errorcheck user input
{
printf("Wrong Input \n");
main();
}//end while
switch (i)
{
case 1:
//Save File
break;
case 2:
//Go Deeper
break;
case 3:
//Exit
break;
}
//Getting Input
int userInput()
{
getchar(); //Fetch user input
i = getchar(); //Assign user input
i -= '0'; //Convert to suitable int
}
The problem with the above example is that when I run it the "userInput();" validator ("Wrong Input") will trigger unless I manually linebreak or input a 'dummy character' infront of my wished menu input.
I know that this is caused because of the multiple (2) "getchar();" calls in "userInput();" however, my menu system has submenus running off the same functionality and if I were to Go deeper and eventually return to the main menu it would skip input unless I used the multiple (2) "getchar();" calls.
How would I go about solving this silly problem universally (inside "userInput();" )?
Any help would be greatly appriciated!
/Dregg