Search code examples
scanfargv

char *argv - float/int numbers


I am getting the numbers from argv[1] and should distinguish between floating and int numbers. So I decided to do it with sscanf.

Trying to convert the string into float - I failed. (if it is an int value, it shouldn't be included in the output.)

Part of the Code:

  float check;
  sscanf(argv[1], "%f", &check) == 1);
  if(check == 1){
     printf("is a float");
  }

The issue is, that sscanf returns 1 even if it is an int value. How can I stop sscanf from returning 1, if it is an int value? I also tried it with strtod, failed again. Any ideas, what am I doing wrong?

Best regards,

Keita


Solution

  • Int values are float values, so if you want to distinguish between float values that are also ints and floats that are not ints, you need to try it as an int first. In addition, scanf, will return success if any prefix matches the specifier and will ignore extra stuff on the end of the string. If you don't want that, you need to use %n and make sure it has consumed the whole string. So you end up with:

    float checkf;
    int checki, len;
    if (sscanf(argv[1], "%d %n", &checki, &len) >= 1 && argv[1][len] == 0) {
        printf("%s is an int\n", argv[i]);
    } else if (sscanf(argv[i], "%f %n", &checkf, &len) >= 1 && argv[i][len] == 0) {
        printf("%s is a float\n", argv[i]);
    } else {
        printf("%s is neither an int nor a float\n", argv[i]);
    }
    

    %n in the format string causes scanf to report how many chars of input have been consumed up to that point in the format -- putting it at the end of the format allows us to check that the end of the format matches the end of the string and there's not other cruft present in the input. In this case a float input like 2.5 looks like an integer 2 followed by the extra string .5 to the first scanf call, so the scanf will succeed (return 1), but len will be set to the offet of the . (so argv[i][len] will be '.', not 0)