如何检查用户是否使用scanf输入整数
我创建了一个程序来制作*'s
的钻石。 我正在寻找一种方法来检查输入的类型是否是C语言中的整数。 如果输入不是整数,我希望它打印一条消息。
这是我到目前为止:
if(scanf("%i", &n) != 1) printf("must enter integer");
但是,如果消息不是整数,则不显示消息。 任何有关此问题的帮助/指导将不胜感激!
你可以用字符串扫描输入然后逐个检查它的字符,这个例子显示结果:
- 0如果不是数字
- 1如果是数字
你可以用它来制作你想要的输出
char n[10]; int i=0; scanf("%s", n); while(n[i] != '\0') { printf("%d", isdigit(n[i])); i++; }
例:
#include #include main() { char n[10]; int i=0, flag=1; scanf("%s", n); while(n[i] != '\0'){ flag = isdigit(n[i]); if (!flag) break; i++; } if(flag) { i=atoi(n); printf("%d", i); } else { printf("it's not integer"); } }
使用fgets()
后跟strtol()
或sscanf(..."%d"...)
。
强大的代码需要处理IO和解析问题。 IMO,这些最好分开完成。
char buf[50]; fgets(buf, sizeof buf, stdin); int n; int end = 0; // use to note end of scanning and catch trailing junk if (sscanf(buf, "%d %n", &n, &end) != 1 || buf[end] != '\0') { printf("must enter integer"); } else { good_input(n); }
注意:
strtol()
是一种更好的方法,但还需要更多的步骤。 例
其他错误检查包括测试fgets()
的结果,并确保n
的范围对于代码是合理的。
注意:
避免在同一代码中混合fgets()
和scanf()
。
{我在这里说scanf()
而不是sscanf()
。 }
建议不要使用scanf()
。
strtol
返回的endPtr将指向转换中使用的最后一个字符。
虽然这确实需要使用类似fgets的东西来检索输入字符串。
个人偏好是scanf用于机器生成的输入而非人为生成。
尝试添加
fflush(stdout);
在printf
。 或者,让printf
输出以\n
结尾的字符串。
假设已经完成此操作,当且仅当未输入整数时,您实际发布的代码才会显示该消息。 您不需要用fgets
或任何东西替换此行。
如果它似乎没有像你期望的那样工作,问题必定在其他地方。 例如,在此行之前的输入中可能还有缓冲区中剩余的字符。 请发布一个显示问题的完整程序以及您提供的输入。
尝试:
#include #define MAX_LEN 64 int main(void) { bool act = true; char input_string[MAX_LEN]; /* character array to store the string */ int i; printf("Enter a string:\n"); fgets(input_string,sizeof(input_string),stdin); /* read the string */ /* print the string by printing each element of the array */ for(i=0; input_string[i] != 10; i++) // \0 = 10 = new line feed { //the number in each digits can be only 0-9.[ASCII 48-57] if (input_string[i] >= 48 and input_string[i] <= 57) continue; else //must include newline feed { act = false; //0 break; } } if (act == false) printf("\nTHIS IS NOT INTEGER!"); else printf("\nTHIS IS INTEGER"); return 0; }
[===>]首先我们使用fgets接收输入。然后它将开始从输入中拉出每个数字(从数字0开始)以检查它是否为数字0-9 [ASCII 48-57],如果它成功循环和非是字符 - 布尔变量'act'仍然是true。因此返回它的整数。