Zak Fayle-Waters Zak Fayle-Waters - 8 months ago 51
C Question

How would I use sscanf to accept zero as an input, but not non-numeric input?

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;


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