0

I am looking to compare a users input to an integer once they enter some type whether that be a string or float etc. into the command line. If the input is not an integer, i want to produce an error message. I have tried using isdigit() and if(atoi(argv[i])>=0) but have had no luck. How do i go about doing this? Thanks in advance.

if( argc != 4 )
{
    printf("invalid.\n");
    error();
}
else if(atoi(argv[1]) >= 1 && atoi(argv[2]) >= 1 && atoi(argv[3]) >= 0){
    N = atoi(argv[1]);
    M = atoi(argv[2]);
    seed = atoi(argv[3]);

    mult(N,M,mat1,mat2,seed);
}
else
{
    printf("invalid argument.\n");
    error();

}

command line input:

$./filename 1 2 e

this still runs my program but i want it to exit when there's a non integer input.

Cipher
  • 3
  • 3
  • 1
    I saw this exact question earlier today. What happened to it? You probably were asked to provide [mcve] and the definition of "no luck". – Eugene Sh. Nov 10 '20 at 21:06
  • 1
    "I have tried ". Please show the code you have tried as a [minimal verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) and describe the errors/ problems you have with it. – kaylum Nov 10 '20 at 21:07
  • I deleted because i thought i had it working, if(atoi(argv[i]) >= 1) works but i need it to work for the integer 0 hence why i reposted. – Cipher Nov 10 '20 at 21:12
  • Thanks for adding the code. But you still have not described a specific error or problem. One big thing is that `atoi` is not suitable for checking whether input string is a valid `int` or not. Use `strtol`. – kaylum Nov 10 '20 at 21:17
  • 1
    [Determine if a C string is a valid int in C](https://stackoverflow.com/questions/9753346/determine-if-a-c-string-is-a-valid-int-in-c) – kaylum Nov 10 '20 at 21:18

1 Answers1

1

Your program treats the third argument differently from the other two because you have atoi(argv[3]) >= 0 whereas the other two atoi() outputs are tested >= 1. A return value of 0 can mean EITHER "I parsed that successfully and got an integer value of 0" OR "I couldn't parse that successfully" so the interpretation is conflated there if you wish to allow value 0 but don't perform additional checks.

Note also that ./filename 1x 2 3 is considered "valid" by your program. You may wish to take additional steps to ensure that the complete argument is a valid integer representation.

A better approach to both of these problems would involve switching to strtol or strtoul instead of atoi.

jez
  • 14,867
  • 5
  • 37
  • 64