扫描为什么一个文件时,我没有得到正确的char值从scanf函数(Linux的ç六)?(Why am

2019-11-03 08:59发布

这是我文件内容

2
00000100+10000001

基本上我想要做的是读入2为int和以下两个0作为一个字符。 我这样做的代码是(将复制和粘贴,但不知道如何从六到记事本,试过( https://stackoverflow.com/questions/26173704/how-to-copy-and-paste-to-another-application -from-Linux的shellvim )

码:

int main(void)
{
    int times;
    scanf("%d",&times);
    printf("Number of times=%d ",times);
    char  num1;
     scanf("%c",&num1);
    char  num2;
    scanf("%c",&num2);
    int n = num1=='0'?0:1;
    int n2 = num2 == '0'?0:1;
printf("The next two digits are %d and %d\n",n,n2);
    return 0;
}

程序编译罚款,我能够从GCC创建可执行文件。 我运行此程序,并重定向标准输入到文件得到的输出是可执行第一个文件重定向命令

$ ./a.out < input.txt

而结果是:

Number of times=2 The next two digits are 1 and 0

两个被正确地打印。 我不明白为什么下一个数字是一个虽然。 从我的理解,不会scanf看到,下一个字符是“0”,或者是有别的东西阻止它? 它最终得到正确的角色,我希望它去,“0”。 有谁知道为什么1被输出。 从我编写的方式(我知道这是不好的设计),任何字符不是“0”将相应的INT设置为1。我只是想知道是什么因素导致这个情况发生,如何避免这个问题。

Answer 1:

你可能认不出来了,但换行字符。
所以num1获取要'\n'因为你的测试( num1 == '0' )不检查空白n变为1 ..

您可以通过在前面的空间避免这种情况%c在scanf。 这将迫使scanf函数忽略空白



文章来源: Why am not getting the right char values from scanf(c Linux vi) when scanning a file?
标签: c linux file