简体   繁体   中英

C++ std::string::assign works strange

need some help from experienced engineers. I've wrote a function, which gets a string and takes a substring from it. Substrings separated from each other with comma ','. I use assign() function to copy substrings. My code:

void my_function(string devices)
{
    unsigned int last=0;
    unsigned int address;
    printf("whole string: %s\n",devices.c_str());

    for (unsigned int z=0; z<devices.size();z++)
    {
        if(devices[z]==',')     
        {
            zone_name.assign(devices,last,z);
            printf("device:%s\n",zone_name.c_str());
            address=get_kd_address_by_name(zone_name);
            last=z+1;
            if(address>0)
            {   
                //doing stuff
            }
        }
    }
}

My problem: only first iteration works. In terminal i get:

whole string: device1,device2,device3,000001029ADA
device:device1
device:device2,device3
device:device3,000001029ADA

Why assign() takes characters after ','?

std::string::assign (the overload you are using) takes a position and a length. Not two positions. z is a position in the devices string. It only works for the first string since in that case, your starting position is 0, so the length and the ending position are the same.

unsigned int length = z - last;
zone.assign(devices, last, length);

If you're just trying to split the string based on some delimiter, why not used boost::split ?

#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>
#include <iostream>

int main(int, char*[])
{
    std::string input("foo,bar,baz");
    std::vector<std::string> output;

    std::cout << "Original: " << input << std::endl;      
    boost::split( output, input, boost::is_any_of(std::string(",")) );
    for( size_t i=0; i<output.size(); ++i )
    {
        std::cout << i << ": " << output[i] << std::endl;
    }

    return 0;
}

Prints:

Original: foo,bar,baz
0: foo
1: bar
2: baz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM