Search code examples
cscanf

scanf in C doesn't fail when formatted text doesn't match


I have hard time understanding how scanf in C works. I need the code below to fail with the input 123 foo.

#include <stdio.h>

int main () {
  int i;
  if (scanf ("%d text", &i) != 1) {
      return 1;
  }
  return 0;
}

I found in C refs that scanf correctly returns the number of successfully assigned arguments (there's 1 specifier in my case), so I can see why the condition in the if statement is satisfied (the integer i is correctly assigned). However I can't see how I check whether the rest of the argument is satisfied as well (string text).


Solution

  • you need to do this manually.

    Example if you want to fail only if user inputs "123 foo"

    int main () 
    {
      int i;
      char s[100];
      if (scanf ("%d %99s", &i, s) == 2 && !strcmp(s, "foo") && i == 123) 
      {
          return 1;
      }
      return 0;
    }