hg_git
hg_git

Reputation: 3084

string to integers from argv

I've a program which is taking input from command-line and using them ahead. All this time the inputs were given separately after the invocation command eg ./a.out 1 2 3 4 5 and it was quite easy to use them (lets just sum them for the moment) -

#include <iostream>
#include <cstdlib>

int main(int argc, char **argv) {
    int sum = 0;
    for(int i = 1; i < argc; ++i) {
        sum += std::atoi(argv[i]);
    }
    std::cout << sum << std::endl;
}

but now the input format has changed to ./a.out "1 2 3 4 5" and this method does not works correctly. I tried to take "1 2 3 4 5" to a string but then I cannot get the integers out of it. Nor can I think of any other solution at this moment. Is there any elegant method to take them out of argv without too much complexity?

Upvotes: 0

Views: 676

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477040

You need to split the string. You can do this for example using string streams:

#include <iostream>
#include <sstream>

int main(int argc, char **argv) {
    int sum = 0;
    for(int i = 1; i < argc; ++i) {
        std::istringstream iss(argv[i]);
        for (int n; iss >> n;) sum += n;
    }
    std::cout << sum << std::endl;
}

Upvotes: 4

Related Questions