GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 28-Sep-2009, 12:09
linan2332's Avatar
linan2332 linan2332 is offline
New Member
 
Join Date: Aug 2009
Location: pleasant hill CA
Posts: 23
linan2332 is on a distinguished road

How to show a number when it is more than int max


Hi,

This is my 7th homework, and I have finish it with no errors.
The program should read an integer number and calculates its number of digits. (For example , 123 has 3 digits)

However, when I type in a number that is more than the maxmium int value, the program will "collapse".
What I want is when I type a number that is more than the int maxmium , it should print "invalid".

Here is the code.
Thanks
--------------------------------------------------------------------------
CPP / C++ / C Code:
/* Lin An ENGIN 135: 09/27/09 */
/* Homework 4 */
/* This program read an integer number and find its number of digits.
The user can test as many numbers as desired without leaving the program */

#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;


int main ()
{

    //declare variables
	long int num , temp(0) , count(0) ;
	char again = 'y';


    //define out object
	ofstream outfile("out.txt");
	outfile<<"VALUE ENTERED"<<setw(20)<<"NUMBER OF DIGITS"<<endl;
	

    while( (again == 'y')||(again == 'Y'))
	{


		cout<<"Enter the number: ";
		cin>>num;
		temp = num;



        //put invalid when number is out of range
		if ( (num>2000000000)||(num<-2000000000) )
		{
			outfile<<temp<<setw(20)<<"Invalid"<<endl;
		}


		//calulate number of digits
		else
		{
			if (num<0)
			{
				num = -num;
			}

			do
			{
				num = num / 10 ;
				count++;
			}while(num!=0);


			
            //write on out.txt
			outfile<<setw(10)<<temp<<setw(15)<<count<<endl;
			cout<<setw(10)<<temp<<setw(15)<<count<<endl;


           //put variable count back to 0
			count = 0;
			
		}
        

		cout<<"Enter Y to continue: ";
		cin>>again;
	}
    

	//close program and outfile
	outfile.close();
	return 0 ;


}
__________________
just started to learn C++ :)
  #2  
Old 28-Sep-2009, 12:16
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 761
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: how to show a number when it is more than int max


An easy way to do this would be to read the input from within a try/catch block. This way, you catch the exception and can print out an error message such as "invalid input".
  #3  
Old 28-Sep-2009, 12:21
linan2332's Avatar
linan2332 linan2332 is offline
New Member
 
Join Date: Aug 2009
Location: pleasant hill CA
Posts: 23
linan2332 is on a distinguished road

Re: how to show a number when it is more than int max


how shall i do it?can u show me?
__________________
just started to learn C++ :)
  #4  
Old 28-Sep-2009, 12:44
linan2332's Avatar
linan2332 linan2332 is offline
New Member
 
Join Date: Aug 2009
Location: pleasant hill CA
Posts: 23
linan2332 is on a distinguished road

Re: how to show a number when it is more than int max


I want to do it like
" the number invalid"
__________________
just started to learn C++ :)
  #5  
Old 28-Sep-2009, 13:08
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 761
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: how to show a number when it is more than int max


See this. Basically, you would put the statement that you convert the user input to an integer in a try{} block. Then catch any exception and print to the error to the screen within the catch(){} block.
  #6  
Old 28-Sep-2009, 14:55
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,310
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: how to show a number when it is more than int max


Quote:
Originally Posted by linan2332
I want to do it like
" the number invalid"

If you read the number into an integer data type and the conversion fails, you have to reset the stream before you can do anything with it. One way might be with a try-catch block, as fakepoo suggested (you clear the error bit and empty out the stream inside the catch block).

Or you can simply test the state of cin after the attempted read. If cin is in the "fail" state, you can clear it and empty the input stream before continuing to ask the user for more input. (No exception stuff here.)

On the other hand if you want to show the user what the invalid data was, I think the only general way is to read user input into a std::string object and then do the conversion. If the conversion fails, you have the original string to put into the user message. You don't need the try-catch stuff here.

One way to convert a "C-Style string" to an integer data type that lets you do some error checking is with the standard library strtol(). (Use the .c_str() member function of the std::string object to get the "C-Style string" corresponding to user input.)

Another way that is preferred by many C++ programmers is to use a C++ stringstream object as follows:
  1. Read the number into a std::string object, not an integer data type object.

  2. Declare a stringstream object, using the string as its initializer

  3. Use the >> operator to extract the value from a stringstream into your number

  4. If the conversion fails, print out the string, otherwise count the digits as you have done.


Regards,

Dave
Last edited by davekw7x : 28-Sep-2009 at 15:32.
  #7  
Old 28-Sep-2009, 14:57
linan2332's Avatar
linan2332 linan2332 is offline
New Member
 
Join Date: Aug 2009
Location: pleasant hill CA
Posts: 23
linan2332 is on a distinguished road

Re: how to show a number when it is more than int max


Thx for the reply!
__________________
just started to learn C++ :)
  #8  
Old 02-Oct-2009, 15:30
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 342
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: how to show a number when it is more than int max


Quote:
Originally Posted by linan2332
how shall i do it?can u show me?

How about:

CPP / C++ / C Code:
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

bool isNegativeInteger(std::string const& str_of_digits)
{
    bool isNegative = false;
    if(str_of_digits.length() > 1)
    {
        if(str_of_digits[0] == '-')
        {
            isNegative = true;
        }
    }
    return isNegative;
}

bool isValidInteger(std::string const& str_of_digits)
{
    bool isValidInteger = true;
    size_t idx = 0;
    if(isNegativeInteger(str_of_digits))
    {
        idx = 1;
    }
    else
    {
        idx = 0;
    }
    if(str_of_digits.length() > 1)
    {
        if(str_of_digits[idx] == '0')
        {
            isValidInteger = false;
        }
    }
    for(; idx < str_of_digits.length(); idx++)
    {
        if(!isdigit(str_of_digits[idx]))
        {
            isValidInteger = false;
            break;
        }
    }
    return isValidInteger;
}


int main()
{
    cout << "Enter a number: ";
    string number;
    getline(cin, number);
    if(isValidInteger(number))
    {
        size_t len = number.length();
        if(isNegativeInteger(number))
        {
            --len;
        }
        cout << "Count of Digits in " << number << " is " << len << endl;
    }
    else
    {
        cout << number << " is an invalid integer!" << endl;
    }
    return 0;
}


Output:

Code:
Enter a number: 123456789012345678901234567890 Count of Digits in 123456789012345678901234567890 is 30 $ ./linan Enter a number: -123456789012345678901234567890 Count of Digits in -123456789012345678901234567890 is 30 $ ./linan Enter a number: -123 Count of Digits in -123 is 3 $ ./linan Enter a number: 123 Count of Digits in 123 is 3 $ ./linan Enter a number: 0192 0192 is an invalid integer! $ ./linan Enter a number: -01 -01 is an invalid integer! $ ./linan Enter a number: -0 -0 is an invalid integer! $ ./linan Enter a number: 1-1 1-1 is an invalid integer! $ ./linan Enter a number: 1.23 1.23 is an invalid integer! $ ./linan Enter a number: 49384827878343891243454543452845709857345634507657409857234557234980745 Count of Digits in 49384827878343891243454543452845709857345634507657409857234557234980745 is 71


MxB
  #9  
Old 02-Oct-2009, 15:42
linan2332's Avatar
linan2332 linan2332 is offline
New Member
 
Join Date: Aug 2009
Location: pleasant hill CA
Posts: 23
linan2332 is on a distinguished road

Re: How to show a number when it is more than int max


well, my teacher haven cover this part of program but still thx!
XD~
__________________
just started to learn C++ :)
 
 

Recent GIDBlogProblems with the Navy (Officers) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to show a 3 digit number with separate digits showing fomi101 C++ Forum 9 29-Sep-2007 13:50
String trim problem and wrong node routing agent! newbie06 Computer Software Forum - Linux 8 01-Mar-2007 23:51
Knights Tour - Reloaded . kobi_hikri C Programming Language 12 03-Oct-2005 12:15
Anyone can write a program code for this??? chriskan76 C Programming Language 1 19-Oct-2004 20:25
Apache2 config issues monev Apache Web Server Forum 2 28-Jun-2004 06:19

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 14:56.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.