【发布时间】: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 甚至没有我输入它!我应该怎么做?
【问题讨论】: