-6

I'm new to C++ and trying to create a program in which the user enters an integer value for number of items wanted. While the program runs with int values, it doesn't work when values like '2.2, 1.34a, b5' are entered.

Here's my program so far:

    int main(){
       int nuts, bolts, screws;

       cout << "Number of nuts: ";
       cin >> nuts;

       cout << "\n\nNumber of bolts: ";
       cin >> bolts;

       cout << "\n\nNumber of screws: ";
       cin >> screws;

       system("cls");

       cout << "Nuts: " << nuts << endl;
       cout << "Bolts: " << nuts << endl;
       cout << "Screws: " << nuts << endl;

       return 0;
    }

Any help would be appreciated. Thanks

1 Answers1

3

When you need to perform error checks on user input, it's best to create a function in which you do the error checks.

int readInt(std::istream& in)
{
   int number;
   while ( ! (in >> number ))
   {
     // If there was an error, clear the stream.
     in.clear();

     // Ignore everything in rest of the line.
     in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

   return number;
}

and then, use:

bolts = readInt(std::cin);

etc.

If you want to bail out when the user provides erroneous input, you can use:

if ( !(cin >> bolts) )
{
    std::cerr << "Bad input.\n";
    return EXIT_FAILURE;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270