Hello fellow coders!

This is my first time and post on forum but hope to stay here seems like a good friendly place

Anyway the following code is to count the number of digits on user input. This includes decimal numbers. So far the code does what it does
1. Can this code be written more better, or possibly using different better objects etc?
2. How to get rid of system("pause")? I'm in the habit of using it and i dunno how to write in a way to halt program so user can see answer. I'm aware of using cin.get etc but don't know how to use it here.

``````#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
// define user input number and counter
long double number; int DigitCount = 0;
cout << "Enter a large number (can include decimal points) :  ";
cin >> number;

// split the number into non decimal and decimal part
int number1;
long double number2;
number1 = (int)floor(number); // store the non-decimal part
number2 = number - number1; // store the decimal part

// count the number of non-decimal integers
while (number1 > 0) 	{
number1 /= 10;
DigitCount++;
}

// count the number of decimal integers
while (number2 - floor(number2+0.0001) > 0.001)	  {
// the while condition ensures that we have the difference
// as zero once the decimal places are all zero
// for some reason if the computer complies to do
// number2 - floor(number2)
// and we know that number2 variable has no decimal places
// the output is not zero, hence the tolerance condition
number2 *= 10;
DigitCount++;
}

// output number of digits for user
cout << "\n\n Your number is " << DigitCount
<< " digits long\n";

system("pause");
return 0;
}``````

You could simply take the input as a std::string and then use yourString.size(). If there were decimals, you could check each character to see if it is a number using something like this: http://www.java2s.com/Tutorial/Cpp/0040__Data-Types/Usingfunctionsisdigit.htm

``````int digitCounter = 0;
for(unsigned int i = 0; i < yourString.size(); i++)
{
if(isdigit(yourString[i]))
{
digitCounter++;
}
}``````

Dave

If you want to have really big numbers then you will need to use strings. if you dont need more then 12-15 digits than you do this

``````#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
long double input;
string number;
cout << "Enter a number: ";
cin >>  input;
cin.ignore(80, '\n');
stringstream converter;
converter << input;
converter >> number;
if (number.find_first_of(".", 0) != string::npos)
cout << "\nthe size of the number is " << number.size() - 1 << " digits.";
else
cout << "\nthe size of the number is " << number.size()<< " digits.";
cin.get();
return 0;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.