What does sscanf do in C if the input doesn't meet the specified format?

154 Views Asked by At
#include <stdio.h>

int main(int argc, const char *argv[]) {
    FILE *fp = fopen("input.txt", "r");
    char buffer[256];
    int n, a, b;
    n = a = b = 0;
    while (fgets(buffer, 250, fp)) {
        n = sscanf(buffer, "%d %d", &a, &b);
        printf("%d %d %d\n", a, b, n);
    }
    fclose(fp);
    printf("Next Part\n");
    fp = fopen("input.txt", "r");
    n = a = b = 0;
    while (0 < (n = fscanf(fp, "%d %d", &a, &b))){
        printf("%d %d %d\n", a, b, n);
    }

    return 0;
}

input.txt contains these lines:

1 2 3
4 abc 5 6
7 8
the 1 next 2 line 3 is blank

4 5 the above line is blank 6
7 8

I know the first printed line will be 1 2 2 because n was set to the return value of sscanf (which returned 2 since both integers were read I assume). I, however, am unsure of what the second line would produce? If I can get someone to work out and explain the second line for me, I would appreciate it. I am also confused on what will happen when the loop experiences a blank line?

2

There are 2 best solutions below

3
Jabberwocky On

Admittedly the sscanf documentation is tedious to read.

This small example shows what happens if the input does not match the format string.

#include <stdio.h>

int main(void)
{
  int a = 100, b = 200;
  char input1[] = "1 2 3 4 whatever";
  int n = sscanf(input1, "%d %d", &a, &b);
  printf("sscanf has read %d items. a = %d, b = %d\n", n, a, b);

  char input2[] = "11 foo bar";
  n = sscanf(input2, "%d %d", &a, &b);
  printf("sscanf has read %d items. a = %d, b = %d\n", n, a, b);
}

The output is:

sscanf has read 2 items. a = 1, b = 2
sscanf has read 1 items. a = 11, b = 2

During the first sscanf, 2 items have been read as 1 and 2 match the %d %d format string.

During the second sscanf, only 1 item has been read as only 11 matches the first %d, but foo does not match the second %d. b is not modified.

It let you figure out what sscanf does if you feed it a blank line. Hint: it's not totally obvious, but it's in the documentation.

2
chux - Reinstate Monica On

What does sscanf do in C if the input doesn't meet the specified format?

int sscanf(const char * restrict s, const char * restrict format, ...);

sscanf() processes the format string format a character at a time if not %. Otherwise it reads a single scan specifier (like "%d"). These are processed against the string s, but no further than the end of string s. sscanf() then continues likewise down format until a null character is read or scan specifier conversions fails. Then:

  • The scanning stops.

  • Subsequent parts of format are not used.

  • There is no further change to the number of conversions (the return value).

  • ... arguments not yet used are left unread so whatever they point to is not assigned.

  • sscanf() returns the conversion count.