【问题标题】:C Programming - Calling fgets() twice?C 编程 - 调用 fgets() 两次?
【发布时间】:2012-03-15 18:23:05
【问题描述】:

在我的 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

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

Type 'C' or 'F': (value)

然后……

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

(Program terminates)

它填写 57.40 甚至没有我输入它!我应该怎么做?

【问题讨论】:

    标签: c input char stdin fgets


    【解决方案1】:
    fgets(str, 2, stdin);
    

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

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

    【讨论】:

    • 我会增加缓冲区并通知您。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2015-06-22
    • 2020-10-25
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多