仅接受使用scanf输入的数值

如何确保用户仅输入数字值而不是字母数字或任何其他字符? 还有什么寻找插入错误信息的incorrent输入?

#include int main() { int a, b, c; printf("Enter first number to add\n"); scanf("%d",&a); printf("Enter second number to add\n"); scanf("%d",&b); c = a + b; printf("Sum of entered numbers = %d\n",c); return 0; } 

如果你真的想处理可能是敌对的用户输入,请使用单独的函数来获取数字。

允许
– 领先的空间:“123”
– 尾随空格:“123”
– 前导零:“0000000000000000000000000000000000123”
– 错误输入后很好地重新扫描。
捕获以下错误
– 没有输入:“”
– 数字后面的额外文字:“123 abc”
– 数字前的文字:“abc 123”
– 分裂编号:“123 456”
– 溢出/下溢:“12345678901234567890”
– 其他:“ – 123”
重新提示无效输入。

 #include  #include  #include  int GetInteger(const char *prompt, int *i) { int Invalid = 0; int EndIndex; char buffer[100]; do { if (Invalid) fputs("Invalid input, try again.\n", stdout); Invalid = 1; fputs(prompt, stdout); if (NULL == fgets(buffer, sizeof(buffer), stdin)) return 1; errno = 0; } while ((1 != sscanf(buffer, "%d %n", i, &EndIndex)) || buffer[EndIndex] || errno); return 0; } int main() { int a, b, c; if (GetInteger("Enter first number to add\n", &a)) { ; // End of file or I/O error (rare) } if (GetInteger("Enter second number to add\n", &b)) { ; // End of file or I/O error (rare) } c = a + b; printf("Sum of entered numbers = %d\n",c); return 0; } 

顺便说一句,你不应该做printf("Enter first number to add\n") 。 请改用fputs() 。 考虑如果字符串中包含% ,会发生什么。

请阅读scanf的手册页。 您需要检查返回值。 如果能够匹配数字,则返回1。

最好避免使用scanf 。 使用fgets获取整行,然后使用sscanf提取所需的信息。 检查sscanf的返回值以确保输入符合预期。

编辑 –我需要在while循环中添加getchar() ,因为未读的非数字项留在输入队列中导致程序进入无限循环,此外我还为while添加了更紧凑的while循环forms同样的事情,两者都会产生同样的效果。

您可以检查scanf的返回值,它在与格式说明符成功匹配时返回1,否则返回0。 你可以为你的程序这样做:

 #include  #include  int main(void) { int num; bool status;//_bool may also be used and stdbool.h won't be needed for that status = scanf ("%d",&num); if (status != 1 ) { getchar();// needed to add it to eat up the unread item left in input queue. while (status != 1) { printf (" sorry ! incorrect input :ERROR: try again"); status = scanf("%d", &num); } } /*....do something...*/ return 0; } 

更简洁的while循环forms : –

 while (scanf("%d",&num) != 1) { getchar(); printf (" sorry ! incorrect input :ERROR: try again\n"); } 

此外,您应该始终为num1num2等变量使用有意义的名称,而不是ab