C beginner here and I'm trying to learn to write a menu program. Below is my code
//A test file to test functions
#include <stdio.h>
#include <stdlib.h>
int enterChangeChar();
void printMenu();
char C = ' ';
int main()
{
char inputVal;
while (1)
{
printMenu();
scanf("%c", &inputVal);
switch (inputVal)
{
case 'c': enterChangeChar(); break;
case 'q': exit(0);
}
}
return 0;
}
int enterChangeChar()
{
int input;
printf("Would you like to Enter or Change the Character value?\n\n");
printf("Enter 1 to Assign OR 2 to Change the value of C: \n");
scanf("%d", &input); //input a integer value
if(input == 1)
{
printf("Enter a character: \n");
scanf(" %c", &C);
printf("You entered: %c", C);
}
else if (input == 2)
{
printf("Change Value option selected\n");
}
return 0;
}
void printMenu()
{
printf("Select a menu choice from the options below: \n\n");
printf(" OPTIONS INPUT\n");
printf("Enter/Change Character 'c'\n");
printf("Quit Program 'q'\n\n");
printf("Enter your CHOICE:\n");
}
when I run the program. The menu is printed twice after I input a character. Why is the program doing so?
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
c
Would you like to Enter or Change the Character value?
Enter 1 to Assign OR 2 to Change the value of C:
1
Enter a character:
v
You entered: v
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
q
EDIT: just added the printMenu() function code which I missed out earlier.
Edit 2: Maybe my question is not clear enough. The problem is not with getchar
and scanf
. The problem is that the menu prints twice after user inputs a character even though it's only called once in the whole program.
Edit 3: Final Edit: Guys I got it now. \n was in the input buffer and whenever choice was given, it was counted as input so the menu was printed multiple times. Thanks for the help.