Validate scanf parameters

2019-07-20 03:06发布

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

标签: c ansi
1条回答
对你真心纯属浪费
2楼-- · 2019-07-20 04:01

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

查看更多
登录 后发表回答