Quick Question

This is a discussion on Quick Question within the C++ Programming forums, part of the General Programming Boards category; Hey all, I have a question. I want to break up an integer by digits. For example, Code: 1234 1 ...

  1. #1
    I Write C++ Apps, Sue Me.
    Join Date
    Feb 2006
    Location
    In My Computer
    Posts
    44

    Quick Question

    Hey all,
    I have a question. I want to break up an integer by digits. For example,
    Code:
    1234
    
    1
    2
    3
    4
    Does anybody know if this is possible to do.
    Thanks,
    Kyle

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    method 1: convert to string, then use/convert individual chars as needed
    method 2: mod by 10 to get last digit, then divide by 10 to remove last digit, repeat till you get to 0

    with method two you are getting the numbers in reverse order so I'd suggest you use a deque and push_front() to automagically arrange them
    Last edited by Darryl; 02-27-2006 at 02:33 PM.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >I have a question. I want to break up an integer by digits.
    One way is to use the modulus (%) operator and division (/) operator in a loop:
    Code:
    //loop
       digit = num % 10;
       num = num / 10;
    //end loop

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Modulus and division, modulus by 10 gets the last digit. Divide by 10 to cut off the last digit:
    Code:
    std::list<int> List;
    
    while(Number > 0)
    {
      List.push_front(Number % 10);
      Number /= 10;
    }
    This will add all digits to the list.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    I Write C++ Apps, Sue Me.
    Join Date
    Feb 2006
    Location
    In My Computer
    Posts
    44
    alright, got it now, thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Very quick math question
    By jverkoey in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 10-26-2005, 11:05 PM
  2. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 03:48 AM
  3. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 04:44 AM
  4. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21