c ++ boost split string

icn*_*icn 50 c++ boost split

我正在使用该boost::split方法拆分字符串,如下所示:

我首先确保包含正确的标题以访问boost::split:

#include <boost/algorithm/string.hpp>
Run Code Online (Sandbox Code Playgroud)

然后:

vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
Run Code Online (Sandbox Code Playgroud)

这条线就像

"test   test2   test3"
Run Code Online (Sandbox Code Playgroud)

这是我使用结果字符串向量的方式:

void printstrs(vector<string> strs)
{
    for(vector<string>::iterator it = strs.begin();it!=strs.end();++it)
    {
        cout << *it << "-------";
    }

    cout << endl;
}
Run Code Online (Sandbox Code Playgroud)

但是为什么在结果中strs我只得到,"test2"而且"test3"不应该"test","test2"并且"test3",\t字符串中有(tab).

2011年4月24日更新:在我更改了一行代码后,printstrs我可以看到第一个字符串.我变了

cout << *it << "-------";
Run Code Online (Sandbox Code Playgroud)

cout << *it << endl;
Run Code Online (Sandbox Code Playgroud)

它似乎"-------"以某种方式覆盖了第一根弦.

kar*_*lip 70

问题出在代码中的其他地方,因为这有效:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;
Run Code Online (Sandbox Code Playgroud)

并测试你的方法,它使用矢量迭代器也有效:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}
Run Code Online (Sandbox Code Playgroud)

同样,你的问题在其他地方.也许您认为\t字符串上的字符不是.我会用调试来填充代码,首先监视向量上的插入,以确保所有内容都按照它应该的方式插入.

输出:

* size of the vector: 3
test
test2
test3
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,本示例中使用了以下 Boost 标头:`#include &lt;boost/algorithm/string/split.hpp&gt;` 和 `#include &lt;boost/algorithm/string/classification.hpp&gt;` (3认同)
  • 如果你不分享一个能够重现你所面临的问题的最小例子,我们就无法为你做任何其他事情.请记住:MINIMAL EXAMPLE,而不是您的完整应用. (2认同)

jam*_*mes 12

我最好猜测为什么你遇到问题 - 覆盖你的第一个结果是你实际从文件中读取输入行.该行最后可能有一个\ r \n,所以你最终得到这样的东西:

-----------test2-------test3

发生的事情是这台机器实际打印出来的:

test-------test2-------test3\r-------

这意味着,由于test3结束时的回车,test3之后的破折号被打印在第一个单词的顶部(以及测试和test2之间的一些现有破折号,但你不会注意到,因为它们是已经破灭了).