Thread: Split int variable

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    7

    Split int variable

    Im VERY new to C++ and programming in general.. so if this is all very simple... sorry.

    Im having trouble trying to divide a number into 2 parts, basically, you have to enter a 7 digit number, and then split it into 2 other int variables, for example, if you entered 1234567, then you would split it so that p1 = 1234 and p2 = 567.

    I cant figure out how to do this...

    this is what the code looks like leading up to that part...

    int main()
    {
    int id, a, b, p1, p2;

    cout<<"Please enter your 7-digit ID: ";
    cin>>id;


    Please help im really stuck....

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Try this:
    Code:
    p2 = id % 1000;
    p1 = id / 1000;
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    Aug 2004
    Location
    San Diego, CA
    Posts
    313
    3-digit part in p1, 4-digit part in p2.

    Code:
    p1 = (id / 10000); // Basically a shift of the decimal point, which ints don't carry past.
    p2 = (id - (p1 * 10000));

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    Thanks alot guys...

  5. #5
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    Would it be possible to use the cin.get function to do this as well ?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  3. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM