My code’s purpose is to take an input of temperature in celsius and convert it to fahrenheit. It is working, but I need to figure out how to reject any non-numeric input. I think I can create an if-loop, but I’m not exactly sure what to put in it in order to differentiate between numeric, and non numeric inputs. I took a screenshot of my code.
![14%20PM|690x398](upload://haqmYaTAaPommPOk3wVtf3fVHVW.png)
<p>
//initializing the libraries
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
//asking the user for the temperature in celsius
float name;
printf("C: "); //asking user for temperature in celsius
scanf("%f", &name);
//converting the temperature to fahrenheit from celsius
float temperature = (name * 9)/5 + 32;
printf("F: %.1f\n", temperature); //displaying temperature in fahrenheit to tenths place
return 0;
}
</p>
I think I can create an if-loop
There is no such thing as an “if-loop”. But you could use a while
loop. What if you had a boolean variable isValidInput that is initially set to false
. The while
loop continues while that is still false
and inside that loop you get the input and if it is valid, you toggle your boolean variable?
I’m skimming your code here but it looks like you just need to say:
if( isalpha(name) ){
printf("F: %.1f\n", temperature);
} else {
printf("Please only use numbers");
}
return(0);