0

The program intends to accept a character(via a function called menu) from the user and print that character(via the main function). However, when this act of accepting and printing the character is iterated more than once, the program does not accept a second value. Instead, the Return key pressed after entering the first value is registered as the next input.

#include <stdio.h>

char menu();

char menu()
{
    char choice;
    printf("Menu (Please enter your choice)\nA/a -> Add an employee\nQ/q -> Quit\n");
    scanf("%c", &choice);

    return choice;
}

int main()
{
    char menu_choice;
    int i;
    for(i=0;i<3;i++)
    {
        menu_choice = menu();
        printf("You've chosen %c\n", menu_choice);
    }
    printf("End\n");
    
    return 0;
}

The picture shows the output received when the process of accepting and printing a character is iterated thrice using a for loop in the main function.

screenshot

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Magic
  • 11
  • 4
  • 2
    `scanf("%c", &choice);`->`scanf(" %c", &choice);` mind the space before `%c`. – kiran Biradar Nov 04 '20 at 05:54
  • What is the question? You perfectly understand what is happening. The main point should be that students shouldn't be invited in writing old style menus with C. – Costantino Grana Nov 04 '20 at 05:57
  • Hi Kiran, your suggestion worked! Thank you. – Magic Nov 04 '20 at 06:01
  • Hi Constantino Grana, I'm brushing up on a few C concepts and ran into this issue when executing a larger piece of code. Since I couldn't understand how to get over this part I isolated this piece of code to get a better understanding from the community. However, the issue is solved now. Thank you for dropping by! – Magic Nov 04 '20 at 06:04
  • @Magic I didn't want to comment on your question specifically. It is just that C has files as an abstraction of input, which is a really bad fit for keyboard input and console output. The best solution is avoiding keyboard input and output while learning, using files on disk for I/O. This way it is possible to inspect every byte you are sending to your program with a debugger avoiding many surprises. – Costantino Grana Nov 04 '20 at 06:36

1 Answers1

0

Quickly written something..., to handle space characters

#include<stdio.h>
#include<ctype.h>
int main()
{
   char ch;
   // skips spaces,' ', '\n', \t' before actual input
   while(isspace(ch = getchar()));
       printf("ch = %c\n", ch);

   // read ch if not space character
   while( !isspace(ch = getchar()))
       printf("ch = %c\n", ch);

  printf("EOP\n");
  return 0;
}
IrAM
  • 1,720
  • 5
  • 18