【问题标题】:How can you recognize with scanf in C that the input is not a number? [duplicate]你如何在 C 中使用 scanf 识别输入不是数字? [复制]
【发布时间】:2021-03-03 20:57:49
【问题描述】:

例如,我如何生成错误消息? 'a' 是输入值?

#include <stdio.h>
    
int main ( void )
{
    int a; 
    scanf ("%d" , & a) ;
    
    // if a is not a number, then generate error
    
    return 0 ;
}

【问题讨论】:

  • 不要使用scanf,使用fgets + strtol
  • 必须是scanf...
  • a 不是整数时是否要生成错误?
  • 是的,就是这样。
  • 检查返回值。 scanf 返回扫描的项目数,或文件末尾的 EOF 或其他错误。比如if (scanf ("%d", &amp;a) == EOF) { ... handle error ...}

标签: c


【解决方案1】:

您想确保scanf 确实正确识别了一个整数,因此检查返回值scanf 系列函数返回一个整数,表示正确解析的元素的数量,因此如果您执行scanf("%d", ...),则在有效整数的情况下,您应该期望返回值1

int a;

if (scanf("%d", &a) != 1) {
    // the value read was not an integer, the end of file was reached, or some other error occurred
} else {
    // good
}

这就是scanf 所能做的全部,然而请注意,遗憾的是,这不足以确保扫描的值确实是由用户,并且它没有溢出。

您可以在 C 中执行此操作的唯一合理方法是首先将输入作为字符串获取,然后使用 strtol 或类似函数对其进行解析,这些函数能够正确报告解析和溢出错误。

【讨论】:

  • 请注意,scanf( "%d", &amp;a) 将接受"12c" 之类的输入 - 它将成功转换并将12 分配给a 并将'c' 留在输入流中以破坏下一个读。您需要检查 scanf 的返回值,您需要检查 not 转换的第一个字符 - 如果它不是空格,那么您不需要t 有一个有效的整数输入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 2010-11-17
相关资源
最近更新 更多