Printf prints optional * mark

I have very simple code to convert upper case to lower case:

#include <stdio.h> int main() { char c; int i=0; for (i=0;i<10;i++){ c=getchar(); c=c-'A'+'a'; printf("%c\n",c ); } return 0; } 

But when you run this simple code, there is always an extra * character in the output. It prints char as follows * . Take a look:

 D d * D d * E e * 

Where did it come from?

+7
c loops getchar
source share
1 answer

After each input, due to pressing the ENTER key, there is a newline , which is stored in the input buffer and read at the next iteration on getchar() .

a newline ( \n ) has an ASCII value of 10 (decimal) added to 'a'-'A' , which is 32 (decimal), produces 42 (decimal), which prints * .

FWIW, getchar() returns int . It’s a good idea to store the return value of getchar() in a char variable, because if getchar() doesn’t work, one of the possible return values, for example EOF , will not fit into char , which causes problems in further conditional verification of even debugging attempts. Edit

 char c; 

to

 int c = 0; 
+12
source share

All Articles