使用scanf()输入validation

我有一个程序接受用户的整数,并在加法操作中使用该数字。

我用来接受这个号码的代码是这样的:

scanf("%d", &num); 

如何validation输入,以便用户输入带小数点的字母或数字时,屏幕上会显示错误消息?

您应该使用scanf返回值。 来自man scanf

回报价值

这些函数返回成功匹配和分配的输入项的数量,这可以少于提供的数量,或者在早期匹配失败的情况下甚至为零。

所以它可能看起来像这样:

 if (scanf("%d", &num) != 1) { /* Display error message. */ } 

请注意,它不适用于“带小数点的数字”。 为此,您应该使用解析和strtol 。 它可能有点复杂。

使用带有%s转换说明符的scanf或使用fgets读取输入为文本,然后使用strtol库函数进行转换:

 #define MAX_DIGITS 20 // maximum number of decimal digits in a 64-bit integer int val; int okay = 0; do { char input[MAX_DIGITS+2]; // +1 for sign, +1 for 0 terminator printf("Gimme a number: "); fflush(stdout); if (fgets(input, sizeof input, stdin)) { char *chk = NULL; // points to the first character *not* converted by strtol val = (int) strtol(input, &chk, 10); if (isspace(*chk) || *chk == 0) { // input was a valid integer string, we're done okay = 1; } else { printf("\"%s\" is not a valid integer string, try again.\n", input); } } } while (!okay);