1

I want to be able to parse a string such as:

inputStr = "abc 12 aa 4 34 2 3 40 3 4 2 cda t 4 car 3"

Into separate vectors (a string vector and integer vector) such that:

strVec = {"abc", "aa", "cda", "t", "car"};
intVec = {12, 4, 34, 2, 3, 40, 3, 4, 2, 4, 3};

What is a good method to do this? I'm somewhat familiar with stringstream and was wondering whether it's possible to do something like this:

std::string str;
int integer;
std::vector<int> intVec;
std::vector<std::string> strVec;
std::istringstream iss(inputStr);

while (!iss.eof()) {
    if (iss >> integer) {
        intVec.push_back(integer);
    } else if (iss >> str) {
        strVec.push_back(str);
    }
}

I have attempted something to that effect, but the program seems to enter a halt of sorts (?). Any advice is much appreciated!

Athena
  • 320
  • 2
  • 12

2 Answers2

1

When iss >> integer fails, the stream is broken, and iss >> str will keep failing. A solution is to use iss.clear() when iss >> integer fails:

if (iss >> integer) {
    intVec.push_back(integer);
} else {
    iss.clear();
    if (iss >> str) strVec.push_back(str);
}
xskxzr
  • 12,442
  • 12
  • 37
  • 77
0

I think this answer is the best here.

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

template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        *(result++) = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}

Originally answered here, You can then try to distinguish between strings and numbers.

Zeyad Etman
  • 2,250
  • 5
  • 25
  • 42