Convert string to int (but only if it is really int)

At college, I was asked if our program showed whether a string from the command line arguments entered an integer that was not ( ./Program 3.7). Now I wonder how I can detect this. Thus, an input, for example, is ainvalid that atoi detects, but an input, such as, for example 3.6, must be invalid, but atoi converts this to an integer.

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        int number = atoi(argv[1]);
        printf("okay\n");
    }
}

But offcourse okay should only be printed if argv [1] is indeed an integer. Hope my question is clear. Many thanks.

+3
source share
4 answers

strtol.

endptr NULL, strtol() * endptr. , , strtol() str * endptr. ( , * str \0' but **endptr is\0 ' , .)

#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc > 1) {
    char* end;
    long number = strtol(argv[1], &end, 0);
    if (*end == '\0')
      printf("okay\n");
  }
}
+9

, , (, ), - , . , :

  • +/-.
  • .
  • ( ).
  • .

, .

- :

set sign to +1.
set gotdigit to false.
set accumulator to 0.
set index to 0.
if char[index] is '+':
    set index to index + 1.
else:
    if char[index] is '-':
        set sign to -1.
        set index to index + 1.
while char[index] not end-of-string:
    if char[index] not numeric:
        return error.
    set accumulator to accumulator * 10 + numeric value of char[index].
    catch overflow here and return error.
    set index to index + 1.
    set gotdigit to true.
if not gotdigit:
    return error.
return sign * accumulator.
+2
int okay = argc>1 && *argv[1];
char* p = argv[1];
int sign = 1;
int value = 0;
if( *p=='-' ) p++, sign=-1;
else if( *p=='+' ) p++;
for( ; *p; p++ ) {
    if( *p>='0' && *p<='9' ) {
        value = 10*value + *p-'0';
    } else {
        okay = 0;
        break;
    }
}
if( okay ) {
    value *= sign;
    printf( "okay, value=%d\n", value );
}

EDIT: allow - + characters

- . ;)

EDIT2: just for fun - now it has to parse the number

+1
source

Source: https://habr.com/ru/post/1727708/


All Articles