1

When i call the function read() without putting a loop or something like that before it works perfectly but when i add some code it doesn't work, here is the code :

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

char read();

int main()
{
    int level = -1;
    char c;
    while (level < 1 || level > 3)
    {
        printf("Select a level 1/2/3 : ");
        scanf("%d", &level);
    }
    printf("Put a character : ");
    c = read();
    printf("Your character : %c", c);
    
    return 0;
}
char read()
{
    char letter;
    letter = getchar();
    letter = toupper(letter);
    while (getchar() != '\n');    
    return letter;
}

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
OtO
  • 21
  • 3
  • Does this answer your question? [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – stark Jul 05 '21 at 13:11

1 Answers1

0

The function getchar reads also white space characters as for example the new line character '\n' that can be placed in the input buffer after the call

scanf("%d", &level);

in the while loop.

Instead of getchar use a call of scanf within the function

char read()
{
    char letter = '\0';
    scanf( " %c", &letter );
    letter = toupper(( unsigned char )letter);
    return letter;
}

Pay attention to the space in the format string before the conversion specifier %c. It allows to skip white spaces in the input stream.

Or the function can look like

char read()
{
    char letter = '\0';

    scanf( " %c", &letter );
    letter = toupper( ( unsigned char )letter );

    int dummy;
    while ( ( dummy = getchar() ) != EOF && dummy != '\n' );

    return letter;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335