I've got this simple program:
#include <stdio.h>
int main()
{
int c;
while ( ( c = getchar()) != EOF)
printf("%d %c\n", c, c);
return 1;
}
However for some reason when executing i get an extra value ten at the end:
a
97 a
10
b
98 b
10
abc
97 a
98 b
99 c
10
What is the value 10 and where does it come from? How do I stop it from occurring?
Solution:
#include <stdio.h>
#include <ctype.h>
int main()
{
int c;
while ( ( c = getchar()) != EOF)
{
if ( isprint (c))
{
printf("%d %c\n", c, c);
}
}
return 1;
}
It's the newline you enter for the input. It has the ASCII value 10.
Here are three ways of "stopping" it:
Add an if
check in the loop to check for it, and print only when it's not a newline.
Use fgets
to read one complete line at a time, remove the newline from the string (fgets
adds it) and loop over the string and print each character.
Use scanf
to read a character. With a leading space in the format it will skip whitespace like newlines.
The first method can be used to check for unprintable characters as well (see isprint
), and other classes of characters if you want to do special printing for them (look at these character classification functions).