I do not understand why my program runs correctly and then when the do...while repeats it enters my else function when I do not want it to. After it does this my program then repeats like I want it to. I am sorry for the poor explanation but I think the picture below "My program" shows better than I can explain what is happening.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float fahrenheit,celsius;
char selection[30];
char *idontknow;
long trueselection;
do{
printf("1: Fahrenheit to Celsius.");
printf("\n2: Celsius to Fahrenheit.");
printf("\n3: Quit program.\n");
fgets(selection,10,stdin); //This line and the line below are in the program
//so that if the user inputs a character instead of an integer it does not infinite loop.
trueselection = strtol(selection, &idontknow, 10);
if(trueselection==1){
printf("Enter temperature in Fahrenheit: ");
scanf("%f",&fahrenheit);
celsius= (fahrenheit - 32) / 1.8;
printf("Temperature in Celsius: %.2f\n\n\n",celsius);
}
else if(trueselection==2){
printf("Enter temperature in Celsius: ");
scanf("%f",&celsius);
fahrenheit= (celsius*1.8)+32;
printf("Temperature in Fahrenheit: %.2f\n\n\n",fahrenheit);
}
else if(trueselection==3){ //This "else if" statement is so the program does not say invalid selection before exiting if 3 is entered.
return 0;
}
else{
printf("Invalid selection !!!\n\n\n");
}
}
while(trueselection!=3); //This line tells the program to repeat back to line 3 if any selection but 3 is selected.
}