Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to int (But only if really is an int)

In college I was asked if our program detects if the string enter from command line arguments is a integer which it did not(./Program 3.7). Now I am wondering how I can detect this. So input as for example a is invalid which atoi detects, but input like for example 3.6 should be invalid but atoi will convert 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 really an integer. Hope my question is clear. Many thanks.

like image 580
Alfred Avatar asked Dec 07 '22 04:12

Alfred


2 Answers

Have a look at strtol.

If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, however, strtol() stores the original value of str in *endptr. (Thus, if *str is not \0' but **endptr is \0' on return, the entire string was valid.)

#include <stdio.h>
#include <stdlib.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");
  }
}
like image 136
Gregory Pakosz Avatar answered Dec 31 '22 01:12

Gregory Pakosz


Assuming you want to know how it could be done in code (possible if it is indeed homework), one way is to think about what constitutes an integer in terms of the string. It would most likely be:

  • an optional sign, +/-.
  • a required digit.
  • any number of optional digits (but watch out for overflow).
  • the end of string.

From that specification, you can write a function that will do the work for you.

Something like this pseudo-code would be a good start:

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.
like image 40
paxdiablo Avatar answered Dec 31 '22 00:12

paxdiablo