C 编程 - 调用 fgets() 两次?

标签 c input char stdin fgets

在我的 C 程序中,我调用了两次 fgets() 以获取用户的输入。但是,在 fgets() 的第二次调用(在函数中)时,它不会等待输入被接受,它只是跳过它,就好像它甚至没有询问一样为了它。这是我的代码(缩短了一点):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ARE_EQUAL 0

void rm_nl(char *c, int s);
float ctof();
float ftoc();

int main()
{   
    char str[2];                                     // Setting vars
    float result;

    printf("Type 'C' or 'F': ");                     // Prompt

    fgets(str, 2, stdin);                            // <-- First fgets
    rm_nl(str, 2);                                   // rm_nl() removes the newline 
                                                     // from input
    printf("\n");

    if(strcmp(str, "C") == ARE_EQUAL || strcmp(str, "c") == ARE_EQUAL)
    {
        result = ctof();                         // Compares strings and calls
        printf("%.2f\n", result);                // function conditionally
    }
    else
    {
        result = ftoc();
        printf("%.2f\n", result);
    }

    return 0;
}

float ctof()                                          // One of the two functions
{                                                     // (they are almost the same) 
    char input[64];
    float fahr, cels;                                 // Local vars

    printf("Type in a Celsius value: ");             // Prompt

    fgets(input, 64, stdin);                               // <-- Second fgets
    rm_nl(input, sizeof(input));

        // Yadda yadda yadda
}


// Second function and rm_nl() not shown for readability

这个程序会输出如下内容:

键入“C”或“F”:(值)

然后……

Type a Celsius value: 57.40 (I don't type this)

(Program terminates)

我什至没有输入它就填入了 57.40!我应该怎么做?

最佳答案

fgets(str, 2, stdin);

您为 fgets 提供的空间太小。您只允许它读取一个字符(因为 2 包含 0 终止符)。

换行符将始终保留在输入缓冲区中,以便下一个 stdio 操作将读取它。

关于C 编程 - 调用 fgets() 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9445368/

相关文章:

java - 我应该在主类或其他地方解析输入参数吗?

javascript - 知道建议打开

angularjs - 在我的 angularjs Controller 中获取 ng-change 字段的值

c++ - 使用fstream方法读取二进制数据

c - sbrk() 是如何工作的?

c - 为什么这个基于scanf和功能的简单程序不起作用?

c - 函数 ‘gmtime_r’ 的隐式声明

创建在另一个头文件中定义的结构数组

c - 需要帮助弄清楚为什么 strtok 导致段错误,它不能使用 const char* 参数吗?

c - 增加 char 数组的最大大小