我的主函数调用另一个函数,它的前 3 行是:
char input[1024];
printf("Please enter the difficulty level between [1-7]:\n");
fgets(input, 1024, stdin);
由于某种原因,fgets 不会等待我的输入。
只是为了澄清 - 第一件事(除了初始化整数和类似的东西)是调用该函数。
并且我没有在整个代码中使用 scanf。
可能是什么问题?谢谢!
编辑:
这是我的主要功能:
int main(){
int check = 0;
char input[1024];
int level = getLevel(); //get the difficulty level from the user
while ( level>7 || level<1 ) level = getLevel();
return level
}
这是 getLevel 函数:
int getLevel(){
int level = 1;
char input[1024];
bool isNum = true;
printf("Please enter the difficulty level between [1-7]:\n");
fgets(input, 1024, stdin); //gets the input from the user
isNum = InputIsInt(input);
if(!isNum){ //input is not a number
return 0;
}
level = atoi(input);
return level;
}
这是 InputIsInt 函数:(工作正常)
bool InputIsInt(const char* str){
if(!str ||!*str){
return false;
}
if(*str=='-'){//if the number is negative
++str;
}
while(((*str)!='\0')&&((*str)!='\n')){
if (!isdigit(*str)){
return false;
}
else{
++str;
}
}
return true;
}
而且,程序不会停止(因为 getLevel 函数一直返回 0)。
另一次编辑:
看来在终端中运行程序确实有效(fgets 正在“等待”我的输入),现在我按照建议更改了 InputIsInt 函数,程序按照我想要的方式运行。
但是仅在终端中。当我尝试在 IDE 中运行它时(我使用的是 Eclipse Neon),fgets 仍然不等待我的输入... 有什么想法吗?
最后一次编辑:
我尝试使用 Virtual Studio 而不是 Eclipse Neon,它似乎解决了我所有的问题(关于这段代码,我的生活仍然一团糟:))。
最佳答案
您没有发布显示该问题的完整程序。
fgets()
不等待输入的一个很可能的原因是,如果您之前已使用 scanf("%d", ...) 解析过其他输入
或 scanf("%s, ...)
。尾随换行符仍在 stdin
缓冲区中等待,并由 fgets()
读取>,因此立即返回。
如果您没有使用 scanf()
,您也可能在 stdin
绑定(bind)到空文件或封闭文件的环境中运行程序。终端。某些IDE存在此问题,请在终端窗口中运行程序。
无论如何,您都应该检查fgets()
的返回值。这是代码的改进版本:
#include <errno.h>
#include <string.h>
#include <stdio.h>
int getLevel(void) {
char input[1024];
printf("Please enter the difficulty level between [1-7]:\n");
if (fgets(input, 1024, stdin) == NULL) {
fprintf(stderr, "fgets failed: %s\n", strerror(errno));
return 0;
}
if (!InputIsInt(input)) { //input is not a number
return 0;
}
return atoi(input);
}
bool InputIsInt(const char *str) {
if (!str || !*str) return false;
if (*str == '-') { //if the number is negative
++str;
}
size_t digits = strspn(str, "0123456789");
return (digits > 0 && (str[digits] == '\0' || str[digits] == '\n');
}
关于c - fgets() 不等待使用 Eclipse-neon 运行的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44739891/