0

I wrote a code to create a glossary of the most basic C instructions, their function and some definition (explained in a very simplistic way).

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int main(void)
{
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int main(void)
{
        char dv = '"';
        char choice;
        int lsel;
        printf("%s", "C GLOSSARY\nInstructions' syntax list, their function and definitions\n\n----------------------------------------------\n");
        printf("%s", "\nType:\n- 'L' to display the list of instructions currently \n  covered in this glossary.");
        printf("%s", "\n- 'E' to exit the program\n");
        do
        {   
            scanf("%c", &choice);
            choice = toupper(choice);
            if(choice != 'L')
                printf("ERROR: invalid option. Please, try again: ");
        } while(choice != 'L');
        if(choice == 'E')
            return 0; //the code continues...
}


        

It works, but the message ERROR: invalid option. Please, try again: is displayed two times! Do you know why? If you want to try the code: https://github.com/AndreMarinelli/C-glossary

Thank you :)

Andrea
  • 3
  • 3
  • 2
    Change ```scanf("%c", &choice);``` to ```scanf(" %c", &choice);``` – programmer Sep 11 '22 at 23:30
  • 2
    Because you are reading the subsequent newline. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Unlike other format specs, `%[]` and `%c` read ***every character*** without filtering leading whitespace. – Weather Vane Sep 11 '22 at 23:32

1 Answers1

1

Change scanf("%c", &choice); to scanf(" %c", &choice);.

The space in the format specifier allows scanf() to consume any amount of leading whitespace in the input.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
programmer
  • 669
  • 3
  • 11