Reputation: 43
Im trying to write a function the converts kelvin to celsius of farenheit based on a user input, i want it to keep prompting the user if they enter an invalid input but no matter the input it prints "Invalid Input" and the loop repeats even though im printing the value of y to test it and it returns as 'C' or 'F'
(ReadChar() just uses scanf and returns the character)
do
{
printf("Choose Celsius or Farenheit (F/C): ");
y = ReadChar();
y = toupper(y);
printf("%c", y);
if ((y != 'C') || (y != 'F'))
{
printf("Invalid Input\n");
}
}while ((y != 'C') || (y != 'F'));
return(y);
Upvotes: 0
Views: 115
Reputation: 1582
See in your while condition you have put OR condition,which is gonna be true,because you can put only on character in y(either 'C' OR 'F'),try &&
inside while like:
do
{
printf("Choose Celsius or Farenheit (F/C): ");
y = ReadChar();
y = toupper(y);
printf("%c", y);
if ((y != 'C') && (y != 'F'))
{
printf("Invalid Input\n");
}
}while ((y != 'C') && (y != 'F'));
return(y);
Upvotes: 0
Reputation: 5098
You inverted your logic incorrectly. Assuming you started with ((y == 'C') || (y == 'F'))
which defines a valid input, and now you want to inverse condition to define an invalid input, you need to change the logic to ((y != 'C') && (y != 'F'))
(see DeMorgans Law).
Upvotes: 2