Losses with a split

I've been trying to split a string into 8 parts. However for some strange reason it loses with many string lengths. I am rather puzzled as to why this and how it would be resolved. So I am here to ask what is wrong with this snippet?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vector <string> ram(8);
void splitData(string &theMainBuffer)
{
	//theMainBuffer assume the string has about 324 chars in it
	int theShift(theMainBuffer.length()/8);
	cout << theShift << "the divide " << theMainBuffer.length() << endl;
	int place(0);
	for(int i = 0; i != 8; i++)
	{
		if(place == theMainBuffer.length())
		{
			cout << "break" << endl;		
		}
		else
		{
			ram[i] = theMainBuffer.substr(place,theShift);
			cout << place << endl;
			place = place + theShift;
		}
	}
				
	theMainBuffer = "";
}
If the string you're trying to "split" has a length that is not evenly divisible by 8, you will lose characters from the string.

You need to account for that in your code. If I have 9 coins and put them in in 8 pots, one of the pots will have more than one coin in it. You just forget about the 9th coin.
So how would I best account for that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::vector<std::string> split( const std::string& str, std::size_t n = 8 )
{
    if( n < 2 ) return { str } ;

    std::vector<std::string> fragments ;

    const auto min_sz = str.size() / n ;
    const auto excess_chars = str.size() % n ;
    const auto max_sz = min_sz + 1 ;

    // the first excess_chars fragments have one character more
    for( std::size_t i = 0 ; i < excess_chars ; ++i ) fragments.push_back( str.substr( i*max_sz, max_sz ) ) ;
    for( std::size_t i = excess_chars ; i < n ; ++i ) fragments.push_back( str.substr( excess_chars + i*min_sz, min_sz ) ) ;

    return fragments ;
}

http://coliru.stacked-crooked.com/a/bd27b78cc3c7112c
Topic archived. No new replies allowed.