如果你真的想处理可能有敌意的用户输入,请使用一个单独的函数来获取数字。
允许:
- 前导空格: " 123"
- 尾随空格: "123 "
- 前导零: "0000000000000000000000000000000000123"
- 错误输入后可以重新扫描。
捕捉以下错误:
- 没有输入:""
- 数字后面有额外文本:"123 abc"
- 数字前面有文本:"abc 123"
- 分割数字:"123 456"
- 上溢/下溢:"12345678901234567890"
- 其它:"--123"
在无效输入时重新提示。
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
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)) {
;
}
if (GetInteger("Enter second number to add\n", &b)) {
;
}
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
顺便说一下,你不应该使用printf("Enter first number to add\n")
。应该使用fputs()
。考虑一下如果字符串中有一个%
会发生什么。
%d
的情况下输入非数值类型的内容,那么scanf将会抛出一个错误。使用scanf()函数的返回值,阅读:Scanf无法第二次执行。 - Grijesh Chauhan