Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf prints additional * character [duplicate]

Tags:

c

loops

getchar

I have a 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 running this simple code always I have an additional * character at output. It prints the char following by a *. Take a look:

D
d
*
D
d
*
E
e
*

Where does this come from?

like image 762
doubleE Avatar asked Jun 23 '16 08:06

doubleE


1 Answers

After each input, due to ENTER key pressed, there's a newline that is stored in the input buffer and read in the next iteration by getchar().

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

FWIW, getchar() returns an int. It's a very bad idea to store the return value of getchar() into a char variable, as, in case, getchar() fails, one of the possible return values, for example EOF will not be fitting into a char type, causing issues in further conditional check of even debuggin attempt. Change

char c;

to

int c = 0;
like image 158
Sourav Ghosh Avatar answered Sep 19 '22 10:09

Sourav Ghosh