c - fgets() 不等待使用 Eclipse-neon 运行的输入

标签 c eclipse eclipse-neon

我的主函数调用另一个函数,它的前 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/

相关文章:

java - Eclipse 上的 Android 项目错误

eclipse - Tomcat 服务器未在 eclipse Neon 上的目标运行时列出

java - Eclipse Neon 快速辅助自动添加@NonNull

c++ - extern "C"不允许 C header 使用 C++ 保留字

c - 有什么理由在 "write-append"之后重新打开为 "read-only"吗?

java - 从SVN导入项目时"Console configuration "myConf "does not exist"

java - 编辑时,空格不会在 java eclipse 中推送单词

c - 如何确保函数中创建的所有线程在同一函数终止之前返回?

c - clEnqueueNDRangeKernel 何时或为何将 Null 作为事件返回?

eclipse - 在 Eclipse Juno 中将 JSF 2.0 更新为 JSF 2.2