0

So when the user types any number other than 1 or 2 then the program works fine. It tells the user that you entered an incorrect option and allows the user to start over. However if the user were to type "i" for example then it doesn't show the error and also doesn't allow the user to start over. How could I fix this?

Here's the code:

#include <stdio.h>

float celsiusToFahrenheit(float);
float fahrenheitToCelsius(float);

int main()
{
    char ans = 'Y';
    int options;
    float fahrenheit, celsius;

    while(ans == 'Y' || ans == 'y')
    {
        puts("\nEnter an option from the list below(1 or 2).");

        printf("\n1.Celsius to Fahrenheit\n"
               "2.Fahrenheit to Celsius\n\n");
        scanf(" %d", &options);

        if((options == 1) || (options == 2))
        {
            if(options == 1)
            {
                printf("\nEnter Celsius: ");
                scanf(" %f", &celsius);

                printf("\n%.2f Fahrenheit.\n", celsiusToFahrenheit(celsius));
            }
            else if(options == 2)
            {
                printf("\nEnter Fahrenheit: ");
                scanf(" %f", &fahrenheit);

                printf("\n%.2f Celsius.\n", fahrenheitToCelsius(fahrenheit));
            }
        }
        else if((options != 1) || (options != 2))
        {
            printf("\nIncorrect option. Please try again.\n");
        }

        printf("\nDo you want to continue?(Y/N): ");
        scanf(" %c", &ans);
    }

    return 0;
}

float celsiusToFahrenheit(float celsius)
{
    return celsius * 9 / 5 + 32;
}
float fahrenheitToCelsius(float fahrenheit)
{
    return (fahrenheit - 32) * 5 / 9;
}
  • 1
    According to the accepted answer of [this post](http://stackoverflow.com/questions/456303/how-to-validate-input-using-scanf), you should use fgets() to read, and sscanf() to parse. – izzy Nov 27 '15 at 00:29

1 Answers1

1

Make use of scanf's return value.