7

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
doubleE
  • 1,027
  • 1
  • 12
  • 32

1 Answers1

10

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;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • So how to get rid of this problem? –  Jun 23 '16 at 08:38
  • 1
    @SuperCoolHandsomeGelBoy Consume the `'\'n` with a dummy `getchar`... or changing the code using `scanf`? many ways – LPs Jun 23 '16 at 08:39
  • These things have been answered 1000 times before. For questions about mysterious input phenomenon caused by trailing new line characters in stdin, please refer to wiki [How to read / parse input in C? The FAQ](http://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) (feel free to improve if something is missing). For questions regarding bugs related to EOF being an int, there's countless duplicates as well. – Lundin Jun 23 '16 at 09:39
  • [This](http://stackoverflow.com/questions/8464030/using-int-for-character-types-when-comparing-with-eof) seems to be a good dupe for "EOF is actually int". – Lundin Jun 23 '16 at 09:43