std::string的split函数

刚刚要找个按空格分离std::string的函数, 结果发现了stackoverflow上的这个问题.

也没仔细看, 直接拿来一试, 靠, 不对啊, 怎么分离后多出个空字符串, 也就是 "abc def" 分离后, 得到的是:

   "abc"

   "def"

   ""

这不科学! 老外在耍我么, 再看原来的回答下面已经有人commet了:

while (iss) { string subs; iss >> subs; cout << "Substring: " << sub << endl; }

满心欢喜的再一试, 靠, 还是不对啊! 老外也太不靠谱了, 再看下面的comment, 乐了:

 @Eduardo: that's wrong too... you need to test iss between trying to stream another value and using that value,
 i.e. string sub; while (iss >> sub) cout << "Substring: " << sub <<
' '; – Tony D Apr 11 '12 at 2:24

感觉老外有时候也是会激动, 手抖的, 哈哈.

拿这位仁兄的代码再试, OK了.

不过这些老外的代码感觉还是不太规范的, 比如在判断iss是否可用的时候, 是直接判断的, 跟进去的话, 可以看到这里其实是调用了这么个函数:

__CLR_OR_THIS_CALL operator void *() const
{
    // test if any stream operation has failed
    return (fail() ? 0 : (void *)this);
}

我在文档里没有找到这个的说明, 所以最后我还是用了比较规范的方式:

std::string str = "abc def";
std::istringstream iss(str);
while (iss.good())
{
    iss >> str;
    std::cout << str << std::endl;
}
原文地址:https://www.cnblogs.com/chaoswong/p/3457849.html