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).
#include <iostream>
#include <string>
#include <vector>
usingnamespace 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';
}
}
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.