我是 C 新手,我检查了一些解决方案,虽然我只能找到字符的东西(并用字符尝试了他们的解决方案),但它不起作用,我想知道为什么我无限循环(也无法输入任何内容)。当我输入例如字母时,我期望的是一个新的输入。
#include <stdio.h>
#pragma warning(disable:4996)
int main(void)
{
float num1;
while (!(scanf("%f", &num1)))
{
scanf("%f", &num1);
}
}
最佳答案
- 当您输入第一个数字时,循环将按预期退出
- 当你输入一个字符时,scanf将返回0,因为它没有读取到正确的输入(因为scanf返回分配的输入项的数量)。因此它进入了 for 循环,但是当你正确输入数字时,你期望 scanf 返回 1 并退出循环。
但是之前的输入仍然保留在缓冲区中。
一种可能的解决方案是
#include <stdio.h>
float get_float_input() {
// Not portable
float num1;
while (!(scanf("%f", &num1))) {
fseek(stdin, 0,
SEEK_END); // to move the file pointer to the end of the buffer
}
return num1;
}
float get_float_input_func() {
// Portable way
float num1;
int ch;
char buff[1024];
while (1) {
if (fgets(buff, sizeof(buff), stdin) == NULL) {
while ((ch = getchar()) != '\n' && ch != EOF)
; // Clearing the input buffer
continue;
}
if (sscanf(buff, "%f", &num1) != 1) {
continue;
}
break;
}
return num1;
}
int main(void) {
float num1;
num1 = get_float_input_func();
printf("%f\n", num1);
return 0;
}
关于C 在 scanf() 处无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52769374/