You are here:

C++/One dimensional arrays

Advertisement


Question
I finally got the code to work properly, except for where to put my error and warning statement.

1) If the user enters a non-int value, message displayed shd be" Error: invalid data" and the program shd exit the loop.
2) If the user enters a valid int which is more than, say 120 yrs(!(1<=ageValue&&AGEvALUE<=120)),
The user sees the message "Warning: age is invalid(must be between 1 and 120). Where would be the best places to place these messages?..Thanks!

/ reading values printing out input in reverse
//**********************************************************************

#include<iostream>
using namespace std;
const int MAX=1000;


int main()
{
  
  int ageValue[MAX];
  int count=0;
  char choice;

  cout<<"Enter the age of the youngest family member:"<<endl;
  cin>>ageValue[count];

  cout<<"Are there any more family members?(Y for yes and N for no)"<<endl;
  cin>>choice;
  
    for(count=1; choice=='Y'||choice=='y'; count++)
    {
         cout<<"Enter the age of the next youngest person"<<endl;
         cin>>ageValue[count];
         
         cout<<"Are there any more family members?(Y for yes and N for no)";
         cin>>choice;
    }     
  
         
    cout<<"Thank you. The ages of your family in reverse order are:"<<endl;
    while(count>0)
    {
     count--;

      cout<<" "<<ageValue[count];
    }
  
    return 0;
  
}

Answer
You should check directly after you have read the value in from the user. You need to test the state of the stream (cin) to see if it is bad (fatal error) or fail (formatting error). The latter is in fact recoverable by clearing the fail bit and ignoring all characters up to the end of the line, so you need not necessarily terminate the loop for this condition. Here is an example:

   if ( cin.good() && ageValue[count]>=0 && ageValue[count]<=120)
   {
       invalidData = false;
   }
   else if ( cin.bad() )
   {
       throw ios_base::failure("std::cin : Stream bad.");
   }
   else if ( cin.eof() )
   {
       throw ios_base::failure("std::cin : Unexpected EOF.");
   }
   else // negative, too large or badly formatted integer
   {
       cout << "Age must between 0 and 120" << endl;

   // Clear only the fail state flag if it is set
   // and ignore any remaining characters on the line
         cin.clear( cin.rdstate() & ~ios::failbit);
         cin.ignore( numeric_limits<streamsize>::max(), '\n' );
   }

You should include <ios> and <limits>.

Now the above code has a few features that you will have to work with to use it:

There is a bool flag invalidData that is initialised to true each time around your input value loop:

   for(count=1; choice=='Y'||choice=='y'; count++)
   {
       bool invalidData( true );
       while (invalidData)
       {
         cout<<"Enter the age of the next youngest person"<<endl;
         cin>>ageValue[count];

         if ( cin.good() && ageValue[count]>=0 && ageValue[count]<=120)
         {
         invalidData = false;
         }
         // ...

         cin.ignore( numeric_limits<streamsize>::max(), '\n' );
         }
        }

    // ...

If the entered value is good then invalidData becomes false and we continue onto the next value.

If anything really bad happens then an exception is thrown. To handle this exception you will have to try the block of code that can throw and catch the exception:

int main()
{
   try
   {
       int ageValue[MAX];

   // ...

   }
   catch ( ios_base::failure & e )
   {
       cout << "FATAL ERROR: " << e.what() << "\n";
   // set return code here if you wish
   }
}

The only real problem is if the user enters a floating point value such as 1.234 The 1 will be read correctly, then the . causes cin to fail as it is not valid for an integer, so the failure comes a little late in this case.

You can of course modify my example code to also throw an exception for badly formatted and/or out of range values. Note that I extended your valid range to include new babies (i.e. those less than 1 year old)!

To be safe I would modify your read-values for-loop thus:

   for (count=1; count<MAX && (choice=='Y'||choice=='y'); count++)

Also get into the habit of preferring pre-increment/decrement (++count and --count) to post-increment/decrement (count++ and count--) in places where either will do. It does not matter at the moment but the pre-increment/decrement form is usually more efficient if you are using a user-defined type that has overloaded these operators such as some implementations of standard C++ library iterator types.

p.s.: if you would still like to know how to 'continue endlessly' then please post me a new question specifically about this topic.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.