简体   繁体   English

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

[英]C Programming - Calling fgets() twice?

In my C program, I call fgets() twice to get input from the user. 在我的C程序中,我调用fgets()两次以获取用户的输入。 However, on the second call of fgets() (which is in a function), it doesn't wait for the input to be taken, it just skips over it as if it didn't even ask for it. 但是,在第二次调用fgets() (在函数中)时,它不会等待输入,它只是跳过它就像它甚至没有要求它一样。 Here is my code (shortened down a bit): 这是我的代码(缩短了一点):

#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

This program would output something like: 该程序将输出如下内容:

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

and then... 然后...

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

(Program terminates)

It fills in the 57.40 without me even typing it! 即使输入它,它也没有我填充57.40! What should I do differently? 我该怎么办?

 fgets(str, 2, stdin); 

You're providing too little space for fgets . 你为fgets提供的空间太小了。 You only allow it to read one character (since 2 includes the 0-terminator). 您只允许它读取一个字符(因为2包含0终结符)。

The newline will always be left in the input buffer so the next stdio operation will read it. 换行符将始终保留在输入缓冲区中,以便下一个stdio操作将读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM