0

fgetc()用来从仅包含数字的文件中读取字符。然后我将字符转换为 int 并打印出来。没关系。但是在打印出所有数字之后,最后我得到了-38-49值。我用谷歌搜索了它,但那里没有任何关于它的信息。在输入文件中,我有以下内容:0105243100000002200000010001318123 outpuf 是这样的:0105243100000002200000010001318123-38-49 我的代码:

do
    {
        c1 = fgetc(fread)-'0';
        if (!isspace(c1))
        {
            printf("%d", c1); 
        }       
        if (feof(fread))
        {
            break;
        }
    } while (1);
4

2 回答 2

1

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';
  // ...
}
于 2014-04-30T12:33:34.877 回答
0

与您一起阅读文件时,应首先fgetc检查,以检测文件的结尾EOF

int c, n;
while ((c = fgetc(f)) != EOF) {
    if (isdigit(c)) {
        n = c - '0';
        printf("%d", n);
    }
}

否则,您使用该EOF值并得到否定结果。

于 2014-04-30T12:44:07.123 回答