如何在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);
}

如果用户输入的数据不是整数类型,我想显示错误。 那么判断输入的数据是整数类型的条件是什么?

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

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

我几天前刚写了这段代码,用于确定用户输入是否为整数。您必须更改 buf 的大小,以防输入太大或 buf 溢出。 也正如 Steve Summit 所说,

Handling bad input is an important but surprisingly hard problem. First you might want to think about which, if any, of these inputs you want to count as wrong: 1, -1, 01, 000001, 1., 1.1, 1x, 1e, 1e1, 100000000000000000, 1000000000000000000000000000. You might also have to think about (a) leading/trailing whitespace, and (b) leading/trailing \n

对于下面的代码,输入如下 1 11.1.11e11xa 被视为 Not Int 而像 100100 100 -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]!='[=10=]';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");
}
}