What is the effect of trailing white space in a scanf() format string?

后端 未结 4 1731
小蘑菇
小蘑菇 2020-11-21 07:01

What is difference between scanf(\"%d\") and scanf(\"%d \") in this code, where the difference is the trailing blank in the format string?

4条回答
  •  野的像风
    2020-11-21 07:17

    The difference (although obvious) is a different format string. If you enter the following line:

    "3  "

    scanf() will return successfully. Otherwise, it depends on your input provided. scanf() essentially skips over whitespace (tabs, spaces, newlines), and searches for alphanumeric values in the input stream. Since this is trailing whitespace, it gets lumped in with the trailing newline character at the end of input when pressing ENTER, so it's of little consequence.

    scanf() expects the input provided to exactly match the format string you provide to it, with the exception that contiguous whitespace characters are compressed to a single whitespace character. This becomes very important if you want to parse large strings of data with it's string-processing equivalent, sscanf().

    A good exercise to further test this would be something like:

    #include
    
    int main(void)
    {
       int a=0,b=0,c=0;
    
       printf("Enter values for A, B, C, in the format: \"A B  -  C\"\n");
       scanf("%d %d  -  %d", &a, &b, &c);
    
       printf("Values: A:%d, B:%d, C:%d\n", a, b, c);
    }
    

    Afterwards, check and see what the values of these integers are after providing both correctly and incorrectly formatted consoled input (ie: spaces and hyphens). Here are a couple example runs. The first used incorrect input, the second used correctly formatted input. Notice that in the first case, C doesn't even get set, as scanf() will provided unexpected behavior if the input and the format strings don't match up. In general, you are better off using something like fgets() to get a string of input from the user, and then use various search functions (ie: strstr(), strch(), strcat, strcpy, etc) to parse your string, as it is much safer than just using scanf() and assuming the user won't make a mistake, either accidentally or deliberately.

    Enter values for A, B, C, in the format: "A B  -  C"
    1 2 3
    Values: A:1, B:2, C:0
    
    Enter values for A, B, C, in the format: "A B  -  C"
    1 2  -  3
    Values: A:1, B:2, C:3
    

    Now, consider one last run: You'll see that scanf() compacts multiple consecutive whitespace characters to a single character, hence why these final runs actually succeeds:

    Enter values for A, B, C, in the format: "A B  -  C"
    1 2 - 3
    Values: A:1, B:2, C:3
    
    Enter values for A, B, C, in the format: "A B  -  C"
    1     2           -                     3
    Values: A:1, B:2, C:3
    

提交回复
热议问题