Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
i need to know how to split a integer into two parts, tried for a long time can't do it with my limited knowledge, example:
int q; \\q=integer to split
int a, b; \\ a= first 4 numbers of q
\\b= last 3 numbers of q
cin >> q \\input is 1234567
a= (first 4 numbers of q)
b= (last 3 numbers of q)how do you do this?
help,please?
ps: i need variables to stay as integers because i need to use arithmatic.
adriantheo

Hi adrian,
I'm no programmer, but it seems you could treat it as a string, split it into the two parts, then convert string to int.
??
M2If at first you don't succeed, you're about average.

#include <stdio.h>
#include <math.h>int main(int argc, char**argv)
{
int q;
int numDigitsOfB;
int divisor;
int a,b;// Set the number of digits desired for b
numDigitsOfB = 3;// Calc 10 to the 'numDigitsOfB' power
divisor = (int)pow(10.0,(double)numDigitsOfB);
q = 1234567;
// To understand why this works, you need to understand integer division in C/C++
a = q / divisor;
b = q % divisor;printf("%d %d %d %d %d\n",numDigitsOfB,divisor,q,a,b);
}
Be sure to come back and let us know if our suggestions helped!

its okay we were all thinking too complex, all that is needed to be done is to divide by 1000. if q= 1234567 and you need the first 4 number all i needed to do is divide q by 1000 that makes a= 1234. To get the last three b=(1000*a)-q. Thanks for your help though, thought of making it string then converting it to an integer, but frankly thought to hard instead of simplifing. THANX
adriantheo

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |