0

Assume I have a program that calculates the result of multiplying two integers together from a string. I use strtol to separate the first part but how do I separate the second int? For example, "12 5" would give a result of 60.

Right now my code looks like:

    int multiply(const char *input) {
        int result = 0;
        char *second_int;
        int i = strtol(input_line, &second_int, 10);

        result = i * second_int;

        return result;

So obviously right now this would give an error since I only converted the first part of the string to an integer. How do I convert the leftover string into an integer? Do I need another strtol line? Do I need to cast it? I'm unsure of how to go about this.

  • You need to invoke `strtol()` a second time, starting at the address returned by the first. That assumes that both invocations will work. Given `"12 15"`, it won't be a problem; given `"a b"`, it will. You can test the result of `strtol()` and the pointer and `errno` (but you need to zero it before you call `strtol()`) to see whether the conversion worked. See [Correct usage of `strtol()`](https://stackoverflow.com/questions/14176123/correct-usage-of-strtol) for the details. – Jonathan Leffler Jan 24 '16 at 17:18
  • 1
    Or a different tack with `if (sscanf(input, "%d%d", &i, &j) == 2) { result = i * j; }` – Weather Vane Jan 24 '16 at 17:20

1 Answers1

2

strtol declaration is as following:

long int strtol(const char *nptr, char **endptr, int base);

and from man strtol:

If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr.

So you can use the value stored in *endptr to start scanning for another value. Example:

char *str="12 5";
char *end;
printf("%ld\n", strtol(str, &end, 10));
printf("%ld\n", strtol(end, &end, 10));

will print:

12
5
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
nsilent22
  • 2,763
  • 10
  • 14