0

I was going to make a loop that if I type the alphabet then the ascii value comes out. Unless I type '0' in.

but result is as below. There is the code that I made below the result. Where the value 10 is coming from?

Press any Alphabet A 65 Press any Alphabet 10 Press any Alphabet

char aski;
while(1) 
{
    printf("Press any Alphabet\n");
    scanf("%c", &aski);
    if (aski == '0') 
        break;
    else
        printf("%d\n", aski);
}
maio290
  • 6,440
  • 1
  • 21
  • 38
shinel38
  • 9
  • 1

2 Answers2

1

scanf reads an extra \n. ASCII of \n is 10. That's why you get 10. I suggest you to use getchar() to read extra \n.

#include <stdio.h>
int main()
{
    char aski;
    while (1)
    {
        printf("Press any Alphabet\n");
        scanf("%c", &aski);
        getchar();
        if (aski == '0')
            break;
        else
            printf("%d\n", aski);
    }

    return 0;
}

The output is:

Press any Alphabet
a
97
Press any Alphabet
b
98

PS: I stopped excution after, entering b.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
0

When you are pressing enter you are in fact creating a \n (new line) This char has the value of 10, which is what is being printed.

char c = '\n';
printf("%d",c);

Would give you 10 as result.

Try this

char aski;
scanf("%c ", &aski);

Notice the space after the %c, this makes sure to read all whitespace inputted.

Sigurd
  • 21
  • 4