Search code examples
cansi-c

Validate scanf parameters


I need to validate the scanf parameters for example

if (scanf("%c,%f,%f", &ch, &p1, &p2) != 3) 
// How can I tell which parameter failed?
// If I want to output message such as "Second parameter must be a real nubmer".

Solution

  • scanf will stop scanning as soon as the first encountered symbol that does not match a format specifier. So if your scanf returns 1 then only the first format parameter was interpreted.

    switch (scanf("%c,%f,%f", &ch, &p1, &p2)) {
      case 0:
      // no parameters were parsed successfully
      case 1:
      // only first parameter succeeded
      case 2:
      // only the first two parameters succeeded
      case 3:
      // all three parameter succeeded
      default:
      // error
    }
    

    Also please note that a return value smaller than the maximum number of successful parses may also indicate an error. In which case you should consult ferror().