为什么在扫描文件时我没有得到正确的char值从scanf函数(C Linux的六)? [英] Why am not getting the right char values from scanf(c Linux vi) when scanning a file?

查看:198
本文介绍了为什么在扫描文件时我没有得到正确的char值从scanf函数(C Linux的六)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文件的内容

2
00000100+10000001

基本上我想做的事情在2为int和以下两个0作为字符被读取。
我的code这样做是(将复制和粘贴,但不知道如何从六到记事本,试过(<一个href=\"http://stackoverflow.com/questions/26173704/how-to-copy-and-paste-to-another-application-from-linux-shellvim\">How复制和粘贴从Linux的shell(VIM)另一个应用程序?)

code:

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创建可执行文件。
和输出,我从运行此程序,并重定向标准输入文件得到
具有可执行首先文件重定向命令

The program compiled fine and I was able to create the executable from gcc. And the output i got from running this program and redirecting standard input to the file is First file redirection command with executable

$ ./a.out < input.txt

和结果:

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

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

The two is printed correctly. I don't understand why the next digit is one though. From my understanding, won't scanf see that the next character is '0', or is there something else blocking it? It does eventually get to the right character I want it to get to, '0'. Does anyone know why the 1 is being outputted. From the way I coded it (I know it's bad design), any char not a '0' will set the corresponding int to 1. I just want to know what element is causing this one to happen and how to avoid this problem.

推荐答案

您可能认不出来了,但换行的的一个字符。结果
因此, NUM1 获取要的'\\ n'因为你的测试( NUM1 ==' 0 )不检查空格 N 变为1 ..

You might not recognize it, but the newline is a character.
So num1 gets to be '\n' and because your test (num1 == '0') doesn't check for whitespace n becomes 1 ..

您可以用prefixing到%C 在scanf中的空间避免这种情况。这将迫使scanf函数忽略空格

You can avoid this by prefixing a space to %c in scanf. This will force scanf to ignore whitespace

这篇关于为什么在扫描文件时我没有得到正确的char值从scanf函数(C Linux的六)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆