Reputation: 35
I want to write an if statement where if the user input is a float then X happens but I don't actually know how to translate this in to code. The code is below so if anyone could help me that would be great.
// declare a variable
float i = 0;
// ask for an input
scanf( "%f", &i );
// if the input is a float
if() <--- DON'T KNOW WHAT TO PUT HERE
{
// print normally
printf();
}
// in all other cases
else
{
// print an error message
printf();
}
Sorry if this is a really simple question but I'm very new to learning C.
Upvotes: 0
Views: 105
Reputation: 104504
Read it as a string first:
char message[100+1];
char *end = NULL;
double result = 0.0;
scanf("%100s", message);
Then try a safe conversion to double:
result = strtod(message, &end);
if ((end == message) || errno == ERANGE)) {
// not a floating point value
}
else {
// is a floating point value - stored in result
}
Upvotes: 1
Reputation: 153348
To test if user input is a float
Step 1: Read input as a string using fgets()
@DeiDei. Best to avoid scanf()
.
char buf[1000];
if (fgets(buf, sizeof buf, stdin) == NULL) {
puts("End-of-file or rare input error occurred");
return;
}
Could test (not shown) if buffer is such that use input was too large. IMO, consider that a hostile attack.
Now parse the string;
errno = 0;
char *endptr;
float f = strtof(buf, &endptr);
if (buf == endptr) {
puts("No conversion");
return;
}
while (isspace((unsigned char) *endptr) endptr++;
if (*endptr) {
puts("trailing junk");
return;
}
if (errno == ERANGE) {
puts("Out of `float` range."); // too big or maybe too small
// suggest continue on and use the +/- HUGE_VALF or wee number.
} else if (errno) {
puts("Implementation additional error.");
return;
}
// use `f`
Upvotes: 1
Reputation: 126193
You check the return value of the scanf
call -- it tells you how many conversions succeeded:
if (scanf("%f", &i) == 1) {
// the input is a float
} else {
// all other cases -- print an error message
}
Upvotes: 1