我正在尝试编写一个程序,用户可以在其中向数组输入值。实际需要的是程序应该针对 char 字符进行验证。因此,如果用户输入一个随机字符,例如'n',程序应该告诉他“你引入了一个字符,请输入一个整数:”。
不使用 char 变量怎么可能做到这一点?
for (i = 1; i <= size; i++) {
printf("Introduce the value #%d of the list: ", i);
scanf("%d", &list[i]);
if () { // I'm blocked right in this line of code.
printf("What you tried to introduce is a char, please input an integer: ");
scanf("%d", &list[i]);
}
提前致谢。
最佳答案
正如@MFisherKDX 所说,检查 scanf
的返回值.来自scanf man page :
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
所以捕获scanf
的返回值在int
变量,然后将该变量与 1
进行比较(在你的情况下,因为你只试图阅读 1 项)应该告诉你是否 scanf
成功读取一个整数值。
然而,有一个nasty pitfall使用 scanf
时你应该知道的。如果你输入 n
在提示符下,scanf
将失败并返回 0
,但它也不会使用您键入的输入。这意味着下次你调用 scanf
,它将读取相同的输入(您键入的 n
字符),然后再次失败。无论您调用多少次scanf
,它都会继续这样做.计算机科学教育 worker 继续教书总是让我感到惊讶 scanf
对学生来说,不仅考虑到这个潜在的陷阱,而且several other pitfalls以及。我希望我每 小时 都能得到五分钱,某个地方的一些 CS 学生努力获得 scanf
按照他们的直觉告诉他们应该的方式行事。我现在应该在自己的私有(private)岛屿上退休了。但我离题了。
绕过这个特殊陷阱的一种方法是检查 scanf
失败,如果是,则故意消耗并丢弃来自 stdin
的所有输入直到并包括下一个换行符或 EOF
, 以先到者为准。
首先让我们看一些未固定代码,如果您输入非整数作为输入,这些代码会导致无限循环:
// Typing the letter 'n' and hitting <Enter> here causes an infinite loop:
int num, status;
while (1) {
printf("Enter a number: ");
status = scanf("%d", &num);
if (status == 1)
printf("OK\n");
else
printf("Invalid number\n");
}
上面的代码(在你输入 n
并点击 <Enter>
之后)将进入一个无限循环,并开始一遍又一遍地喷出“无效数字”。同样,这是因为 n
您输入的内容永远不会从输入缓冲区中清除。
有a few possible ways to get around this problem , 但共识似乎是最便携和可靠的方法如下:
// Fixed. No more infinite loop.
int num, status;
while (1) {
printf("Enter a number: ");
status = scanf("%d", &num);
if (status == 1)
printf("OK\n");
else {
printf("Invalid number\n");
// Consume the bad input, so it doesn't keep getting re-read by scanf
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) ;
if (ch == EOF) break;
}
}
关于c - 根据字符验证整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388635/