How to use sscanf correctly and safely

后端 未结 3 423
长情又很酷
长情又很酷 2020-12-01 19:49

First of all, other questions about usage of sscanf do not answer my question because the common answer is to not use sscanf at all and use f

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 20:12

    If you must use scanf to accept the input, I think you start with something a bit like the following.

    int array[MAX];
    int i, n;
    scanf("%d", &n);
    for (i = 0; i < n && !feof(stdin); i++) {
        scanf("%d", &array[i]);
    }
    

    This will handle (more or less) the free-format input problem since scanf will automatically skip leading whitespace when matching a %d format.

    The key observation for many of the rest of your concerns is that scanf tells you how many format codes it parsed successfully. So,

    int matches = scanf("%d", &array[i]);
    if (matches == 0) {
       /* no integer in the input stream */
    }
    

    I think this handles directly concerns (3) and (4)

    By itself, this doesn't quite handle the case of the input12a3. The first time through the loop, scanf would parse '12as an integer 12, leaving the remaininga3` for the next loop. You would get an error the next time round, though. Is that good enough for your professor's purposes?

    For integers larger than maxint, eg, "999999.......999", I'm not sure what you can do with straight scanf.

    For inputs larger than the input array, this isn't a scanf problem per se. You just need to count how many integers you've parsed so far.

    If you're allowed to use sscanf to decode strings after they've been extracted from the input stream by something like scanf("%s") you could also do something like this:

    while (...) {
        scanf("%s", buf);
        /* use strtol or sscanf if you really have to */
    }
    

    This works for any sequence of white-space separated words, and lets you separate scanning the input for words, and then seeing if those words look like numbers or not. And, if you have to, you can use scanf variants for each part.

提交回复
热议问题