Why am not getting the right char values from scan

2019-09-17 03:07发布

This is the contents of my file

2
00000100+10000001

Basically what I want to do is read in the 2 as an int and the two following 0s as chars. My code for doing is (would copy and paste but don't know how from vi into notepad, tried (https://stackoverflow.com/questions/26173704/how-to-copy-and-paste-to-another-application-from-linux-shellvim)

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;
}

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

And the result:

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

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.

标签: c linux file
1条回答
劫难
2楼-- · 2019-09-17 03:21

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 ..

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

查看更多
登录 后发表回答