1

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 ','?

Bauhaus
  • 509
  • 8
  • 22
r_spb
  • 75
  • 1
  • 14
  • 1st hint: remove TAB characters (replace by for spaces) from verbatim copied code. – πάντα ῥεῖ Jul 29 '14 at 18:05
  • "zone_name" is not declared....please post code that at least compiles... – jpo38 Jul 29 '14 at 18:06
  • I know that isnt your question but, if you want to know different ways to split a string in tokens or like to see different solutions, check out [this SO question](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c). – wendelbsilva Jul 29 '14 at 18:18

2 Answers2

8

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);
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
1

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
pzed
  • 817
  • 5
  • 8