Reputation: 13
I'm trying to make an algorithm that takes command line input and divides [1] by [2] (given that [1] and [2] are numbers, and [2] is not 0) but
if ((atof(argv[2]) == 0))
accepts both letters and numbers for some reason.
My current code cannot differentiate between 0 and letters. How do I fix this? I only started coding a week ago so I'm sorry if my code is messy and thank you for anything you can say to help.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
if ((atof(argv[2]) == 0))
{
printf("invalid input - divide by zero not allowed\n");
return 0;
}
else if ((atof(argv[1])) && (atof(argv[2])))
{
float sum = 0;
sum = (atof(argv[1])) / (atof(argv[2]));
printf("%f\n", sum);
return 0;
}
else
printf("invalid input\n");
return 0;
}
Upvotes: 0
Views: 75
Reputation: 1059
you should use strtof function instead of atof
float strtof(const char *nptr, char **endptr);
nptr is the pointer to the string you want to interpret as a float. endptr has to be the address of a char pointer (that's why it has double star, it's a pointer to a char pointer).
the function stores the address of the first character past the last character interpreted in the char pointer pointed by endptr.
If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.
Upvotes: 1
Reputation: 16421
You can use isdigit
to tell whether a character is a digit (you still have to convert it to the digit's value later).
But what you really want is to use sscanf
/strtof
(atof
has no way to tell you it failed) and not worry about manual string to digit conversion.
float numerator, denominator;
bool success = sscanf(argv[1], "%f", &numerator) == 1;
success = success && (sscanf(argv[2], "%f", &denominator) == 1);
if(success && denominator != 0) { // float to value comparison is almost always a bad idea
printf("Fraction: %f\n", numerator/denominator);
} else {
printf("Failure\n");
}
Upvotes: 3