PDA

View Full Version : Need help for a beginner Programmer


kiosk55
10-27-2005, 05:42 PM
This is for a C++ class

I have an assignment for school to input a 4 digit integer, but for each of the numbers that is entered I need to assign to a variable to do manuplation with each value.

I am thinking I need to use the cin.get() for my program, but now sure how to assign each value to a variable

For example:

Enter a 4 digit number: 4569 (only limit it to max of 4 values!)

Now assign the first digit (4) to a variable, the 2nd digit (5) to a variable and so on.

Thanks for the help!

TheShaner
10-27-2005, 08:07 PM
There are probably many ways to do this and probably a better method than this, but to me, this is the simplest.

Make sure it's 4 digits long by checking if it's between 1000 - 9999, inclusive. Then, to get each number, just use some basic math.

ThousandsDigit = (int) (number / 1000)
temp = number - (ThousandsDigit * 1000)
HundredsDigit = (int) (temp / 100)
temp = temp - (HundredsDigit * 100)
TensDigit = (int) (temp / 10)
OnesDigit = (int) (temp - (TensDigit * 10))

Do the above code on paper to see how it works. There are other variations to this on how to extract each number, but I liked this method the best. Another method would be utilizing the modulus (%) operator. So play around with the above so that you understand it.

-Shane