0

I am trying to split a string which is given from the getline(cin, str) in a function which is not main().

I have copied the string split code from this link but it throws a bad_alloc error from xmemory when I try to execute it.

I have used the first answer and also tried to use boost::algorithm::string::split but this method also throws the same exception that I encountered.

I think this exception arises from vector<string> memory allocation, but I have no idea how to fix this exception.

I am using visual studio 2017 and windows 10 build 1607 x64. The code was tested on two machines and throws the exception at the same line with ntdll.dll associated with it.

Here is my code:

// code from the link
template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss;
    ss.str(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;
}

// my code
void readScript(string* command, int* col, int* row, MineSweeper* m)
{

    cout << "Input command separated by space: ";
    string str;
    getline(cin, str);
    vector<string> tokens;
    tokens = split(str, ' ');
}
yjs990427
  • 1
  • 3
  • 1
    Please post a [mcve]. It's most likely that the problem is caused by code that is not posted. I tried the posted code and it works as intended. – R Sahu Jul 17 '17 at 03:34
  • Actually, I have tried to compile the whole code with g++ 7.1.0, and it works... Should I think this error come from the compiler? – yjs990427 Jul 17 '17 at 11:37
  • It's hard telling what could be wrong with a [mcve]. – R Sahu Jul 17 '17 at 13:32
  • I fixed it somehow by looking over all the code but still couldn't figure what cause the problem but thanks though. – yjs990427 Jul 17 '17 at 23:01

0 Answers0