В моей программе на C я вызываю fgets()
дважды, чтобы получить вход от пользователя. Однако при втором вызове fgets()
(который находится в функции) он не ждет ввода ввода, он просто пропускает его, как будто он даже не просил об этом. Вот мой код (укороченный немного вниз):C Программирование - вызов 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 без меня даже набрав его! Что мне делать по-другому?
Я увеличу буфер и дам вам знать. Благодаря! –
Работал отлично! Благодаря!! –