我可以在没有 return 键 'n' 的情况下读入一个字符吗? (C)
Can I read in a character without the return key 'n'? (C)
我正在尝试验证用户输入的 return 值是否正确。
他应该输入 0 到 100 之间的偶数。
我想我做对了,但现在我的问题是,用户必须输入两次 "enter" 键才能结束 scanf 功能。
我是否还有另一种可能来避免用户这样做?
这是我写的代码:
#include <stdio.h>
#include <windows.h>
int main( void )
{
int ok, input = -1;
char c;
while(input < 1 || input > 100 || input%2 != 0) { //repeat loop if Input is not even or betwenn 0 and 100
printf("Enter an odd number between 1 und 100: ");
int ok = scanf("%d%c", &input, &c); //Input is correct if ok = 2 and c = 10'\n'
while((c = getchar()) != '\n' && c != EOF) {} //this loop empties the input buffer to avoid infinite loops if users enters a character
}
printf("You habe chosen the number %d ", input);
getchar();
return 0;
}
我相信您根本不需要第二个 while 循环。
如上所示,scanf()
等待输入一次,然后 getchar()
等待。
如果删除第二个 while 循环,代码应该 运行 正确并且只需要按一次回车键。
希望对您有所帮助!
我正在尝试验证用户输入的 return 值是否正确。 他应该输入 0 到 100 之间的偶数。
我想我做对了,但现在我的问题是,用户必须输入两次 "enter" 键才能结束 scanf 功能。
我是否还有另一种可能来避免用户这样做?
这是我写的代码:
#include <stdio.h>
#include <windows.h>
int main( void )
{
int ok, input = -1;
char c;
while(input < 1 || input > 100 || input%2 != 0) { //repeat loop if Input is not even or betwenn 0 and 100
printf("Enter an odd number between 1 und 100: ");
int ok = scanf("%d%c", &input, &c); //Input is correct if ok = 2 and c = 10'\n'
while((c = getchar()) != '\n' && c != EOF) {} //this loop empties the input buffer to avoid infinite loops if users enters a character
}
printf("You habe chosen the number %d ", input);
getchar();
return 0;
}
我相信您根本不需要第二个 while 循环。
如上所示,scanf()
等待输入一次,然后 getchar()
等待。
如果删除第二个 while 循环,代码应该 运行 正确并且只需要按一次回车键。
希望对您有所帮助!