0

I want to keep entering a character till a '*' is entered and change the case of the character. The code I have written is

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
char character;
char con_char;

while(1)
    {
    printf("Enter a character:");
    scanf("%c",&character);
    printf("ASCII value of %c is %d\n", character, character);
    if (character=='*')
        {
            printf("The program terminates\n");
            
            exit(0);
        }
    else if (character>='a' && character<='z')
        {
        con_char = toupper(character);
        printf("%c\t\t%c\n", character, con_char);
        }
    else if (character>='A' && character<='Z')
        {
        con_char = tolower(character);
        printf("%c\t\t%c\n", character, con_char);
        }
    else
        {
        con_char=character;
        printf("%c\t\t%c\n", character, con_char);
        }
    }
return 0;
}

The program works well but only for the format of the output. The line "Enter a character" is displayed in the output two times for a single input. I am not able to understand the reason. Please help. Output:

Enter a character:f ASCII value of f is 102 f F Enter a character:ASCII value of is 10

Enter a character:

  • Please change `scanf("%c",&character);` to `scanf(" %c",&character);` (a space is added) and read [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Nov 01 '20 at 19:11
  • Thanks for the help...it really works.....but I am still not able to reason it out..please explain – user3705890 Nov 02 '20 at 19:52
  • The format specifiers `%d` and `%s` and `%f` automatically filter leading whitespace, but `%c` and `%[...]` and `%n` do not. You can instruct `scanf` to do so by adding a space just before the `%`. The `scanf` conversion stops at the first character it cannot convert, which is typically (but not necessarily) a space or a newline, and that character remains in the input buffer. – Weather Vane Nov 02 '20 at 19:56

0 Answers0