Or, an easier way to read a whole number:
Code:
#include <iostream>
#include <cctype>
#include <fstream>
#include <limits>
using namespace std;
struct inventory_items
{
int code,quantity,reorder_level;
char name[100], units[100];
double price;
};
int main()
{
int counter=0;
inventory_items s;
while (counter==0)
{
cout<<"Enter the item code.\n";
cin>>s.code;
if(!cin)
{
cout << "\nInvalid input" <<endl;
cin.clear();
cin.ignore(std::numeric_limits < int >::max(), '\n');
}
else
{
cout<<"You entered : "<<s.code<<endl;
counter=1;
}
}
return 0;
}
One note, if someone enters "10254rgh", it is seen as a valid input of "10254". Also, you're always going to leave something in the input stream, so you may want to do the clear/ignore no matter what:
Code:
int main()
{
int counter=0;
inventory_items s;
while (counter==0)
{
cout<<"Enter the item code.\n";
cin>>s.code;
if(!cin)
{
cout << "\nInvalid input" <<endl;
}
else
{
cout<<"You entered : "<<s.code<<endl;
counter=1;
}
cin.clear();
cin.ignore(std::numeric_limits < int >::max(), '\n');
}
return 0;
}