CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2011
    Posts
    2

    Try Catch Question

    I need to use try...catch so if the user enters more then 10 digits

    Code:
    #include <iostream>
    
    int main( int argc, const char*argv )
    {
    	int numInput = 0, avgCount = 0, totalCount = 0;  
    	float average = 0;
    
    	while( numInput != 99 )
    	{
    		
    		std::cout << "Enter a Number (Max 10 digits)(99 to Exit): ";
    		std::cin >> numInput;
    
    		if ( numInput != 99 )
    		{
    			totalCount += numInput;
    			avgCount += 1;
    		}
    	}
    	
    	try
    	{
    		if( avgCount == 0 )
    		{
    			throw 0;
    		}
    		average = totalCount / avgCount;
    	}
    	catch(...)
    	{
    		std::cout << "Divide by Zero error" << std::endl;
    		totalCount = 0;
    	}
    	
    	std::cout << "Average of all Inputs: " << average << std::endl;
    
    	system("pause");
    	return 0;
    }
    Last edited by Marc G; February 17th, 2011 at 09:53 AM. Reason: added code tags

  2. #2
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: Try Catch Question

    Please use code tags for posting code.

    I need to use try...catch so if the user enters more then 10 digits
    If you have a question, it helps to actually ask the question.

  3. #3
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: Try Catch Question

    Your main signature is wrong. It should be:
    Code:
    int main()
    Code:
    int main(int argc, char** argv)
    Don't use system("pause"), seePause Before Exiting a Console Application

    Use code tags to post code.

    So check the length of user input, read the user input as a string. Then you can count the number of characters and convert it to an int.
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  4. #4
    Join Date
    Feb 2011
    Posts
    2

    Re: Try Catch Question

    thank you

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

Featured