Validate scanf parameters

若如初见. 提交于 2019-12-12 19:33:12

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/23497475/validate-scanf-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!