0

I need to accept an array of integers from the command line, such as: ./test 2 9 -5 17

Currently I have:

int main(int argc, int *argv[])

And then loops to find the two numbers within this array that create the maximum value possible starting with argv[1]. Obviously this does not work. Do I need it to be:

int main(int argc, char *argv[])

and then parse this? I am not sure how to covert characters to integers in C.

Thanks,

5
  • What is the range of acceptable integers? Commented Apr 11, 2016 at 18:19
  • I am not sure how to covert characters to integers in C. atoi() or strtol() will work to convert a string to an int Commented Apr 11, 2016 at 18:30
  • There is no range. Any integers, positive and negative, large/small, are to be accepted. Commented Apr 11, 2016 at 18:31
  • JDeffo: "no range. Any integers" --> So values like 123456789012345678901234567890 are acceptable? Commented Apr 11, 2016 at 18:40
  • @Mike Holt OP may want to limit code's operation to integers within the range of some C integer type like int of long long or maybe not. It would be illuminating to know OP's thoughts on the coding goals. Commented Apr 11, 2016 at 18:47

2 Answers 2

1

Use strtol() to convert each argv[i] (for i starting at 1) to a long int.

Sign up to request clarification or add additional context in comments.

Comments

0
int main(int argc, char *argv[])
{
    size_t i;
    int n;

    for (i = 0; i < argc; ++i) {
        if (sscanf(argv[i], "%d", &n) == 0) {
            fprintf(stderr, "Position %d is not an int\n", i + 1);
            return 1;
        }
        printf("%d\n", n);
    }

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.