将一串随机序列的字符和整数解析为单独的向量

时间:2018-04-26 01:53:22

标签: c++ parsing

我希望能够解析一个字符串,例如:

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

进入单独的向量(字符串向量和整数向量),使得:

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

这样做的好方法是什么?我对stringstream有点熟悉,并且想知道是否可以这样做:

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);
    }
}

我尝试了一些这样的效果,但程序似乎进入了各种各样的停顿(?)。任何建议都非常感谢!

2 个答案:

答案 0 :(得分:1)

iss >> integer失败时,流会中断,iss >> str会一直失败。解决方案是在iss.clear()失败时使用iss >> integer

if (iss >> integer) {
    intVec.push_back(integer);
} else {
    iss.clear();
    if (iss >> str) strVec.push_back(str);
}

答案 1 :(得分:0)

我认为这个答案是最好的。

#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;
}

最初回答here,然后您可以尝试区分字符串和数字。