I want to input a character and get corresponding ASCII integer as output. I'm using getchar() to take input, create an infinite loop with while, the loop will break when 'q' is entered. My code is -
#include <stdio.h>
int main() {
int c;
printf("Enter a character(press q to exit):\n");
while(1) {
c = getchar();
printf("%d\n",c);
if(c == 'q')
break;
}
printf("End of the program");
return 0;
}
The program is running fine when q is entered, exiting the program. But if I enter any other character, the numerical value is having a 10 added in the end. for example, if I enter i, the output is
Enter a character(press q to exit):
i
105
10
I
73
10
Any character is having that 10 added at the end. What am I doing wrong?
10is the ASCII linefeed character which is being placed in the buffer by virtue of the fact you're pressing ENTER at the end of each line.If you want to ignore those characters, just don't act on them:
Note that I'm also checking for end of file in the loop, otherwise the return value will cause a rather annoying infinite loop.