Results 1 to 3 of 3

Thread: division and modulus operator

  1. #1

    Thread Starter
    Member
    Join Date
    Aug 2000
    Posts
    59

    Cool division and modulus operator

    I need Help,

    How do you separate a number into its individual digits using
    the division and modulus operator??

    For Example:

    if a user enters a string of number say:

    Code:
    cout << "Enter 5 numbers ";
    cin >> numbers;
    
    how do you separate each one???
    say if the user enters 54345
    
    how do you separate the five from the rest, then the four...etc..
    thanks in advanced.

  2. #2
    Zaei
    Guest
    If that is the scenario you have, its simple. You can use a for loop to read in 5 characters, and subtract '0' from each one =).

    Otherwise, you can start at 10000, and work down to 10:
    Code:
    _5 = num / 10000;
    num%=10000;
    _4 = num / 1000;
    num%=1000;
    ...
    _1 = num;
    This works because when you divide, you are doing an integer divide, so it just throws the other numbers away. The mod, on the other hand, just throws the actual integer part away, and gives you what is left.

    Z.

  3. #3
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    you could do the following with any amount of digits
    Code:
    cout << n%10;
    for(;n; )cout<<((n/=10)%10);
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width