Devide integer in parts

How do I make a code where an integer is divided in parts? So if I have an int: for example 605938843, I want as output: 6, 0593, 8843 (parts with length 4). Or 605, 938, 843 (parts with length 3). Or 6059 38843 (parts with length 5).

Thanks.
What code have you written so far?
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;


vector<string> split( const string &str, int len )
{
   vector<string> result;
   if ( len > str.size() ) len = str.size();

   // First item
   int p = str.size() % len;
   if ( p ) result.push_back( str.substr( 0, p ) );

   // Remainder
   for ( ; p < str.size(); p += len ) result.push_back( str.substr( p, len ) );
   return result;
}


int main()
{
   string test = "605938843";
   for ( int len = 2; len <= test.size(); len++ )
   {
      cout << len << ":  ";
      for ( string s : split( test, len ) ) cout << s << ' ';
      cout << '\n';
   }
}


2:  6 05 93 88 43 
3:  605 938 843 
4:  6 0593 8843 
5:  6059 38843 
6:  605 938843 
7:  60 5938843 
8:  6 05938843 
9:  605938843 
I tried it by myself with pointers but that didn't work out. Is it possible to do it with pointers?
Why on earth would you want to do it with pointers?
Show us what didn't work.
yes, you can do things with pointers when none are required, same as you can take the area of a square using calculus & a bit of creativity. It is a great deal of extra code that would largely be hard to follow, less efficient, and generally bad.

you can do the string stuff, for example, using C-string pointers.
something along these lines:

char messy[1000];
uint64_t derpy = 1234567890ull;
sprintf(messy, "%i", derpy);
char* pm = &messy[3];
for(;pm++;) //chop out whatever substring you need.
cout << *pm;
and you can atoi it back into an int after you get a chunk if you need that.

isnt it beautiful? Ok, I was a little sarcastic there and made it extra ugly, but still... the point remains. If it isnt right, its harder to debug, and even if it is right, its harder to read and write and all.
Last edited on
Another way is to use localizations. Consider:

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
#include <iostream>

struct comma_facet : public std::numpunct<char> {
	explicit comma_facet(size_t group) :g(group) {}
	virtual char do_thousands_sep() const { return ','; }
	virtual std::string do_grouping() const { return std::string(1, g); }
	size_t g {};
};

auto set000s(std::ostream& os, size_t group)
{
	return os.imbue(std::locale(os.getloc(), new comma_facet (group)));
}

int main()
{
	int i {605938843};
	set000s(std::cout, 3);
	std::cout << i << '\n';

	set000s(std::cout, 4);
	std::cout << i << '\n';

	set000s(std::cout, 5);
	std::cout << i << '\n';
}



605,938,843
6,0593,8843
6059,38843


Last edited on
Topic archived. No new replies allowed.