tokenizing strings

closed account (SECMoG1T)
i need a hand here, a got this function that is supposed to tokenize pipe "|" dilimited words from a larger string, it should be working fine according to my logic but am ending up with incorrect results, help me debug it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 std::vector<std::string> splice(const std::string& str)
{
    std::size_t pos=0,nextpos=0;
    std::vector<std::string> local;
    while(true)
    {

       nextpos=str.find('|',nextpos);
       if(nextpos==std::string::npos)
         {nextpos=str.size();}

       local.emplace_back(str,pos,nextpos);

       if(nextpos==str.size())
          break;
       ++nextpos;pos=nextpos;
    }

    return local;
}

int main()
{

  auto rslt=splice(std::string("@#XC322-xc|loc3455-xc|xc-0001xc|dr-loch-xc|fp2-09222-xc|dw-877str-xc|08188"));

    for(const auto& val : rslt)
    {
        std::cout<<val<<"  ";
    }


expected

 @#XC322-xc loc3455-xc xc-0001xc dr-loch-xc fp2-09222-xc dw-877str-xc 08188


actual

@#XC322-xc loc3455-xc|xc- xc-0001xc|dr-lo xc-0001xc|dr-loch-xc dr-loch-xc|fp2-09222-xc|dw-877str-xc dw-877str-xc|dw-877str-xc 08188


Thanks Andy.
local.emplace_back(str,pos,nextpos - pos);

At least that's what I think...
This worked:

1
2
std::string temp = str.substr(pos, nextpos - pos);
local.emplace_back(temp);
Last edited on
closed account (SECMoG1T)
Straight from heaven , that's what i needed thank you very much @fg109 i just couldn't think right, hehe :D.
Last edited on
Topic archived. No new replies allowed.