Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading