0

I'm a beginner. So i'm trying to make to conditional statement to make sure that argv is a positive int. For that I need ascii code of argv[1]. And I was planning to make an if condition statement which will be executed only if argv[1]/ascii codes of 0-9 is 1.

Dai
  • 141,631
  • 28
  • 261
  • 374
Abel
  • 1
  • 2
    I think you need to make a distinction between the ASCII code of a one-letter string passed as an argument, and the integer value of a numeric text string passed. In the first case you might be passed the string `"1"` whose ASCII value is `49`, but the numerical equivalent is `1`. – Weather Vane Dec 26 '19 at 17:42

2 Answers2

2

Don't think of low-level ASCII codes (what if the machine isn't using ASCII?). Just use the character constants in expressions:

if (*argv[1] >= '0' && *argv[1] <= '9')
    do stuff

Even better, use isdigit from ctype.h:

if (isdigit(*argv[1]))
    do stuff

The asterisk before argv[1] is the dereferencing operator. In this case it gets the first character of argv[1].

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • Using character constants in range expressions don't work with EBDIC (because _of course_ IBM chooses to be difficult), unfortunately. I think the only thing that C requires of a character-set is that `'0' < '9'`, other than that you need to stick to functions like `isdigit`, etc. http://ascii-table.com/ebcdic-table.php – Dai Dec 26 '19 at 17:43
  • 2
    @Dai the numeric characters `'0'` to `'9'` are guaranteed to be consecutive by the C standard, but only them. – Weather Vane Dec 26 '19 at 17:45
1

So i'm trying to make to conditional statement to make sure that argv is a positive int.

Okay...

For that I need ascii code of argv[1].

No, you don't. You should use strtol instead:

if( argc >= 2 ) {

    char* text = argv[1];

    long value = strtol( text, /*end:*/ NULL, /*base:*/ 10 );
    if( errno != 0 ) { // See https://stackoverflow.com/questions/26080829/detecting-strtol-failure/26083517 
        // `text` is not a valid integer or other parse error
    }
    else {
        if( value > 0 ) {
            // do stuff
        }
        else {
            // value is an integer that's zero or negative
        }
    }
}

And I was planning to make an if condition statement which will be executed only if argv[1]/ascii codes of 0-9 is 1.

That doesn't work if the text value is greater than 9.

Dai
  • 141,631
  • 28
  • 261
  • 374