Reputation: 1391
I'm using fgetc()
to read a char from a file which consists of digits only. Then I convert the characters to int and print it out. That's fine. But after printing out all the digits, at the end I get -38-49
values. I googled it, but nothing about it there.
In the input file, I have the following: 0105243100000002200000010001318123
The outpuf is like this: 0105243100000002200000010001318123-38-49
My code:
do
{
c1 = fgetc(fread)-'0';
if (!isspace(c1))
{
printf("%d", c1);
}
if (feof(fread))
{
break;
}
} while (1);
Upvotes: 0
Views: 551
Reputation: 74028
When reading a file with fgetc
you should check for EOF
first, to detect the end of the file
int c, n;
while ((c = fgetc(f)) != EOF) {
if (isdigit(c)) {
n = c - '0';
printf("%d", n);
}
}
Otherwise, you use the EOF
value and get the negative result.
Upvotes: 0
Reputation: 513
You are reading the newline (10) and the EOF return value of fgetc (-1). Substracting '0' (48) from those yields those negative numbers.
Check if the char if valid, it must be in range ['0','9']
c1 = fgetc(fread);
if(c1 >= '0' && c1 <= '9') {
c1 -= '0';
// ...
}
Upvotes: 1