c-如何防止用户不得不在终端中按两次回车键才能获得输出



我不明白为什么输入整数时必须按两次回车键?我认为这是由于(fgetc(stdin) != 'n');函数。这是为了在输入字母时阻止其无限循环。

如何避免必须按两次回车键才能获得输出?

我只是想验证是否输入了一个数字因此,如果输入了字母,它将提示用户重新输入

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
double val;
char follow;
int count = 0;
int main(void) {
while (count < 1) {
printf("enter an number n");
int read = scanf_s("%lf%c", & val, & follow);
while (fgetc(stdin) != 'n'); //prevent unlimited loop with character. Potential reason for pressing enter twice. 
count = 0;
if (read == 2) {
if (isspace(follow)) {
printf("input is an integer followed by whitespace, accept n");
printf("%lf", val);
count = count + 1;
} else {
printf("input is an integer followed by non-whitespace, reject");
}
} else if (read == 1) {
printf("input is an integer followed by EOF, accept");
printf("%lf", val);
count = count + 1;
} else {
printf("input is not an integer, reject");
}
}
}

只需将while (fgetc(stdin) != 'n');移动到else和else-if语句下方

switch (number) {
case 1:
printf("Managersn");

while (count < 1) {
printf("enter an numbern");
int read = scanf_s("%lf%c", &val, &follow);

if (read == 2) {
if (isspace(follow)) {
printf("input is an integer followed by whitespace, accept n");
printf("%lf", val);
count = count + 1;
}
else {
printf("input is an integer followed by non-whitespace, reject");
while (fgetc(stdin) != 'n'); //prevent unlimited loop with character. Potential reason for pressing enter twice. 
}
}
else if (read == 1) {
printf("input is an integer followed by EOF, accept");
printf("%lf", val);
count = count + 1;
}
else {
printf("input is not an integer, reject");
while (fgetc(stdin) != 'n'); //prevent unlimited loop with character. Potential reason for pressing enter twice. 
}
}

相关内容

  • 没有找到相关文章

最新更新