splitting numbers
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
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.
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.
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.
Homepage
Luck is a Horse to ride like any other...Luckily im not a gambler, I dont know how to ride.
Off the top of my head:
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]
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]
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 :\
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 :\
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement