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