Computing.Net > Forums > Programming > c++ integer into two

Computing.Net: Over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to sign up now, it's free!

c++ integer into two

Reply to Message Icon

Original Message
Name: adriantheo
Date: April 1, 2005 at 02:25:44 Pacific
Subject: c++ integer into two
OS: windows
CPU/Ram: 1
Comment:

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



Report Offensive Message For Removal


Response Number 1
Name: Mechanix2Go
Date: April 1, 2005 at 04:05:59 Pacific
Reply: (edit)

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.

??


M2

If at first you don't succeed, you're about average.


Report Offensive Follow Up For Removal

Response Number 2
Name: Don Arnett
Date: April 1, 2005 at 11:02:17 Pacific
Reply: (edit)

#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!


Report Offensive Follow Up For Removal

Response Number 3
Name: gimmpy225
Date: April 2, 2005 at 18:29:58 Pacific
Reply: (edit)

couldnt you just make the integer an array and then read off the different cells you need?

GIMPS


Report Offensive Follow Up For Removal

Response Number 4
Name: adriantheo
Date: April 4, 2005 at 01:32:39 Pacific
Reply: (edit)

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


Report Offensive Follow Up For Removal







Post Locked

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


Go to Programming Forum Home








Do you own an iPhone?

Yes
No, but soon
No


View Results

Poll Finishes In 7 Days.
Discuss in The Lounge
Poll History




Data Recovery Software