whitespace in the format string (scanf)

前端 未结 4 1953
日久生厌
日久生厌 2020-12-05 12:23

Consider the following code:

#include
int main() {
    int i=3, j=4;
    scanf(\"%d c %d\",&i,&j);
    printf(\"%d %d\",i,j);
    retu         


        
相关标签:
4条回答
  • 2020-12-05 12:43

    Force a string parsing first :

    char a[100], b[100];
    scanf("%99s c %99s", a, b);
    

    Then use sscanf() to convert the strings to int.

    0 讨论(0)
  • 2020-12-05 12:49

    If you want to accept 1c2 but not 1 c 2, use the pattern without the space:

    scanf("%dc%d", &x, &y);
    

    If you want to accept 1c2 and 1 c 2 (and also 1 \t \t c \t 2 etc), use the pattern with the space:

    scanf("%d c %d", &x, &y);
    

    If you want to accept 1 c 2 but not 1c2, add a fake string containing whitespace:

    scanf("%d%*[ \t]c%*[ \t]%d", &x, &y);
    

    Here the format string %[ \t] would mean "read a string that contains any number of space and tab characters"; but using the additional *, it becomes "expect a string that contains any number of space and tab characters; then discard it"

    0 讨论(0)
  • 2020-12-05 12:53

    I think I would read the scanf result into different variables (i.e. not reuse i and j) as "%d%s%d". Then check the string you got from the %s and if it matches your requirements, use the other variables to overwrite i and j.

    0 讨论(0)
  • 2020-12-05 12:57

    Whitespace in the format string matches 0 or more whitespace characters in the input.

    So "%d c %d" expects number, then any amount of whitespace characters, then character c, then any amount of whitespace characters and another number at the end.

    "%dc%d" expects number, c, number.


    Also note, that if you use * in the format string, it suppresses assignment:
    %*c = read 1 character, but don't assign it to any variable

    So you can use "%d%*c c%*c %d" if you want to force user to enter: number, at least 1 character followed by any amount of whitespace characters, c, at least 1 character followed by any amount of whitespace characters again and number.

    0 讨论(0)
提交回复
热议问题