0

absolute beginner here. This is actually my first little coding project I've done after a small amount of reading on c. here's my code.

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

int main()
{
float temperature;
float cels, fahr, kel;



printf("Please enter your temperature.\n\n");

scanf("%f", &temperature);

fflush(stdin);

printf("\n\nIs this in fahrenheit, celsius, or kelvin? (type f,c, or k)\n");

char c;

c = getchar();

if (c == 'f')
    fahr = temperature;

else if(c == 'c')
    cels = temperature;

else if(c == 'k')
    kel = temperature;


if (fahr = temperature){
    cels = (5*(fahr-32))/9;
    kel = cels +273;
}

else if (cels = temperature){
    kel = cels + 273;
    fahr = ((9 * cels)/5)+32;
}

else if (kel = temperature){
        cels = kel - 273;
        fahr = ((9 * cels)/5)+32;
}


printf("\nOkay, so the temperatures are:\n");

printf("fahr: %f\tcels: %f\tkal: %f\n" , fahr, cels, kel);
return 0;
}

The code is supposed to ask for a temperature value, check based on a user input if that temperature is in fahrenheit, celsius or kelvin, then it finds what the input temperature equals in the other terms, and outputs those values.

I'm pretty sure the problem I'm running into is that the buffer still has an value when I use c = getchar to see if the temperature is in fahr, cels, or kel, therefore the program doesn't wait for a user input at that line of code. I know now that fflush(stdin); is not ideal at all in clearing the buffer and I'm not sure why (like I said, complete beginner here). Anyways any enlightenment into clearing the buffer or even more on how the buffer input works would be greatly appreciated. Thanks.

  • 2
    The second if/else series is not doing what you expect because you are using `=` instead of `==` for testing value – cedrou Nov 16 '17 at 16:53
  • and then you can merge the 2 if/else if into only one: if (c=='f') { fahr = temperature; cels=... ; kel=... } else if (...) – cedrou Nov 16 '17 at 16:55
  • Please see [scanf() leaves the new line char in buffer?](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer) – Weather Vane Nov 16 '17 at 16:59
  • 1
    Note that `fflush(stdin);` is non-standard. Although it is allowed in MSVC, its use is otherwise *undefined behaviour*. – Weather Vane Nov 16 '17 at 17:07

0 Answers0