• Advertisement

Archived

This topic is now archived and is closed to further replies.

splitting numbers

This topic is 5468 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

what would be the easiest way to split a number from a simgle input like "1234" into two separate numbers, "12" and "34"? i am confused :> thanks

Share this post


Link to post
Share on other sites
Advertisement
The easiest way is to first have it as a string (either a char[] or std::string), then simply:

std::string input
std::cin >> input;

std::string part1(input, 0, 2);
std::string part2(input, 2, 2);

If you provide more context and details of what you''re trying to do, a more appropriate example can be made.


Share this post


Link to post
Share on other sites
Well with chars you can do arrays but... for ints i have absolutly no idea. Why do you need this, is there a specific reason. Becasue if there isnt then you are wasting a lot of your time

Homepage
Luck is a Horse to ride like any other...Luckily im not a gambler, I dont know how to ride.

Share this post


Link to post
Share on other sites
Off the top of my head:


    
void splitNumber( int iInput, int* iLeftHalf, int* iRightHalf )
{
int digits = ( (int)( log( (double)iInput ) / log( 10.0 ) ) ) + 1;
*iLeftHalf = iInput / (int)pow( 10.0, (double)(digits / 2) );
*iRightHalf = iInput % (int)pow( 10.0, (double)(digits / 2) );
}


Something like that. Odd LENGTH numbers will be heavier on the left side...dunno what you need.

-scott

[edit: forgot the world "length"]

[edited by - scaught on January 28, 2003 9:01:41 PM]

Share this post


Link to post
Share on other sites
hrmm
perhaps i should have mentioned that it is always 4 digits long

i just figured it out though
i can just divide by 100 then truncate since it is int status
and go from there:


int main()
{
int hey;
int left;
int right;
cin >> hey;

left = hey / 100;
left *= 100;
right = hey - left;
left /= 100;

cout << hey << " " << endl << left << " " << right << endl;
return 0;
}


thanks for the help, even though i wanst exactly clear :\

Share this post


Link to post
Share on other sites

  • Advertisement