Zak Fayle-Waters - 1 year ago 67

C Question

In the below example, I want to be able to accept 0 as a numerator, but not a denominator. I also wish to exclude input of characters that are not numeric. I feel like I'm missing something very simple, or don't quite understand how to use sscanf.

`#include <stdio.h>`

int main(int argc, char *argv[]) {

double numerator = 0.0;

double denominator = 0.0;

double result = 0.0;

if (argc == 3.0) {

sscanf(argv[1],"%lf", &numerator);

sscanf(argv[2],"%lf", &denominator);

result = numerator / denominator;

if (denominator == 0){

printf("invalid input - divide by zero not allowed\n");

}

else if (numerator == 0){

printf("invalid input\n");

}

else printf("%lf\n", result);

}

return 0;

}

Answer Source

The idiomatic way to use the scanf family function to make shure that input is valid is to try to read *something* after the number and control that you only get one single value:

```
if (argc == 3) {
char dummy[2];
if (sscanf(argv[1],"%lf%1s", &numerator, dummy) != 1) {
printf("%s is not a valid input\n", argv[1]);
return 1;
}
...
sscanf(argv[2],"%lf", &denominator);
```

`%1s`

will only allow blank characters (mainly space or newline) after input