A common piece of code I use for simple string splitting looks like this:
inline std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
Someone mentioned that this will silently "swallow" errors occurring in std::getline
. And of course I agree that's the case. But it occurred to me, what could possibly go wrong here in practice that I would need to worry about. basically it all boils down to this:
inline std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
if(/* what error can I catch here? */) {
// *** How did we get here!? ***
}
return elems;
}
A stringstream
is backed by a string
, so we don't have to worry about any of the issues associated with reading from a file. There is no type conversion going on here since getline
simply reads until it sees the line delimeter or EOF. So we can't get any of the errors that something like boost::lexical_cast
has to worry about.
I simply can't think of something besides failing to allocate enough memory that could go wrong, but that'll just throw a std::bad_alloc
well before the std::getline
even takes place. What am I missing?