验证scanf参数 [英] Validate scanf parameters

查看:122
本文介绍了验证scanf参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证scanf参数 例如

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

推荐答案

scanf将在遇到的第一个符号与格式说明符不匹配时立即停止扫描.因此,如果您的scanf返回1,则仅解释第一个format参数.

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
}

还请注意,返回值小于成功分析的最大数目也可能表示错误.在这种情况下,您应该咨询ferror().

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

这篇关于验证scanf参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆