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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With