0

I made a simple code that converts Celsius to Fahrenheit and vice versa, but for some reason, whenever I make an input other than 'C' or 'F' for the unit, it gives me 2 error messages instead of one. How do I get rid of this??

Here's the code:

int main() {
    
    printf("Temperature Unit Converter\n\n");
    
    start:
    
    char unit;
    double temp;
    printf("Enter unit of measurement (C or F): ");
    scanf("%c", &unit);
    unit = toupper(unit);
    
    if (unit == 'C') {
        printf("\nEnter temperature in %c: ", unit);
        scanf("%lf", &temp);
        temp = (temp * 9/5) + 32;
        printf("\nThe temperature = %.1lf degrees Fahrenheit", temp);
    }
    
    else if (unit == 'F') {
        printf("\nEnter temperature in %c: ", unit);
        scanf("%lf", &temp);
        temp = (temp - 32) * 5/9;
        printf("\nThe temperature = %.1lf degrees Celsius", temp);
    }
    
    else {
        printf("\nYou have entered an invalid unit. Please try again.\n");
        goto start;
    }

    return 0;

I also tried inputting the unit with getchar(), and using an else if (unit != 'C' && unit != 'F') instead, but they both gave me the same result.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • So the solution is to filter leading whitespace with `scanf(" %c", &unit);`. Notice the added space. Understanding how whitespace is used by the `scanf` family, by various format specifiers, and in the input stream is *essential* to using the these functions successfully. – Weather Vane Jun 14 '23 at 19:57
  • ... *and* using the function's [return value](https://stackoverflow.com/questions/10469643/what-does-the-scanf-function-return). – Weather Vane Jun 14 '23 at 20:47
  • @WeatherVane woah that did the trick. I'm gonna properly research how the scanf family interacts with white spaces, but the code now works as intended. Thank you! – Elias Xambali Jun 15 '23 at 16:34

0 Answers0