0

In my xml file I have arrays of ints written as follows: "1 10 -5 150 35", and I am using pugixml to parse it.

I know pugixml provides methods such as as_bool, or as_int, but does it provide an easy way of converting the string representation of an int array to a c++ object, or do I have to parse and separate the string myself? If so, any suggestions on how to do that?

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • C++ array or `std::vector` ? – hmjd Jul 24 '12 at 15:08
  • 1
    If each element is separated by exactly on space, use a split function to get the individual elements (as std::strings). Search this site for such a function. Then you can use strtol to convert the std::string to ints. – Anon Mail Jul 24 '12 at 15:10

1 Answers1

3

A possibility would be to use std::istringstream. Examples:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    {
        std::istringstream in(std::string("1 10 -5 150 35"));
        std::vector<int> my_ints;

        std::copy(std::istream_iterator<int>(in),
                  std::istream_iterator<int>(),
                  std::back_inserter(my_ints));
    }

    // Or:
    {
        int i;
        std::istringstream in(std::string("1 10 -5 150 35"));
        std::vector<int> my_ints;
        while (in >> i) my_ints.push_back(i);
    }
    return 0;
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • This code wouldn't compile for me until I added std::istringstream::in as a second parameter to the std::istringstream constructor (in your second example). Without that it would give me "error C2296: '>>' : illegal, left operand has type 'std::istringstream (__cdecl *)(std::string)'" errors. – Lanaru Jul 24 '12 at 15:58
  • @Lanaru, g++ fine with it: http://ideone.com/UCI1Y. What version of VC are you using ? – hmjd Jul 24 '12 at 16:01
  • Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86. The important part is that the code worked perfectly once I added the second parameter to the constructor, although the fact that it didn't compile at first is a bit puzzling. – Lanaru Jul 24 '12 at 16:05
  • 1
    @Lanaru you likely tried to do something like this: http://ideone.com/stjns. Unfortunately, due to C++ grammar pecularities this syntax defines a function instead of creating an object. Adding an extra argument is one way of resolving this (there are others, i.e. add extra parentheses: std::istringstream in((std::string(str))); – zeuxcg Jul 30 '12 at 13:17