Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,911 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,185 people online right now. Registration is fast and FREE... Join Now!




Counting numbers in an integer

 
Reply to this topicStart new topic

Counting numbers in an integer

janandrada
5 Jan, 2008 - 06:53 AM
Post #1

New D.I.C Head
*

Joined: 27 Sep, 2007
Posts: 37


My Contributions
how can a program counts the number in an inputted integer?
ie, input: 24854203
output: 8 numbers

here's my code:
CODE

int x;

cout << "Input an integer: ";
cin >> x;

int y = 0;
for(int i = 1; i < 10; i++){
    if(y <= x)
}

User is offlineProfile CardPM
+Quote Post

PennyBoki
RE: Counting Numbers In An Integer
5 Jan, 2008 - 07:03 AM
Post #2

system("revolution");
Group Icon

Joined: 11 Dec, 2006
Posts: 2,011



Thanked: 7 times
Dream Kudos: 500
Expert In: Java,C++,C

My Contributions
Well a hint would be:
use the div operator that is / in your loop. So while x div 10 is different than 0 counter++.
Then just print the counter+1.

Hope this helps.
User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Counting Numbers In An Integer
5 Jan, 2008 - 07:04 AM
Post #3

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,351



Thanked: 51 times
Dream Kudos: 25
My Contributions
Another method would be to take the input as a string, then manipulate it, perhaps using the .length() method. Especially given that you may overflow the size of the int variable getting untested user input.
User is online!Profile CardPM
+Quote Post

DPR
RE: Counting Numbers In An Integer
5 Jan, 2008 - 12:29 PM
Post #4

New D.I.C Head
*

Joined: 20 Dec, 2006
Posts: 17


My Contributions
The best way I can think of within about 10 seconds and without detailed thought would be to simply divide by ten and floor the result (maintaining it's integer-ness), and add a number to a counter each iteration.
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Counting Numbers In An Integer
5 Jan, 2008 - 02:48 PM
Post #5

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
Using floor() is not necessary; integer division results in the truncation of any non-integral component of the quotient.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 01:56PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month