繁体   English   中英

c - 如何检查输入数据是否正确

[英]how to check input data is correct or not in c

#include<stdio.h>
int main()
{
  int n;
  printf("write any integer:\n");
  scanf("%d",&n);
}

如果用户输入的数据不是整数类型,我想显示错误。 那么我们可以通过什么条件来确定输入的数据是整数类型呢?

如果我写了一个整数类型的字符(让 'a'),那么如何识别输入的数据不是整数,然后显示“你没有输入整数”的错误。

我认为可以通过使用 scanf() 的返回类型或类型转换来实现,但我不确定它是否有效以及如何工作?

几天前我刚刚写了这段代码,用于确定用户输入是否为整数。 您必须更改buf的大小,以防输入过大或buf溢出。 同样正如史蒂夫·萨米特所说,

处理错误的输入是一个重要但非常困难的问题。 首先,您可能需要考虑将这些输入中的哪些(如果有)计为错误: 1, -1, 01, 000001, 1., 1.1, 1x, 1e, 1e1, 100000000000000000, 10000000000000000考虑 (a) 前导/尾随空格,和 (b) 前导/尾随 \\n

在下面的代码的情况下,像1 11.1.11e11xa这样的输入被认为Not Int而像100100100-10这样的输入被认为是Int

#include<stdio.h>
#include<ctype.h> //using ctype.h as suggested by Steve Summit
int check(char *buf){ //for checking trailing whitespace characters
  for(int i=0;buf[i]!='\0';i++){
   if(!isspace(buf[i])){
      return 0;
    }
  }
  return 1;
}
int main(){
int x;
char buf[10]; //change buf to appropriate length based on the input or it may overflow
scanf("%d",&x);
if(scanf("%[^\n]",buf)==0||check(buf)){
  printf("Int");
}
else{
  printf("Not Int");
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM