Reputation: 7
void addItem(struct InventoryItem inventory[], int& size){
cout << "\nEnter the item name: ";
cin.getline(inventory[size].itemName, 100, '\n');
while (strlen(inventory[size].itemName) == 0){
cout << "Invalid item name!" << endl;
cout << "Enter item name: ";
cin.getline(inventory[size].itemName, MAX_CHAR, '\n');
}
cout << "Enter the item price: ";
cin >> inventory[size].itemPrice;
while(!cin || inventory[size].itemPrice < 0){
cout << "Please enter a valid number: ";
cin >> inventory[size].itemPrice;
clear();
}
cout << endl;
size++;
}
My !cin
keeps accepting letters as numbers ...
any ideas why?
note: I'm new to programming.
Upvotes: 0
Views: 60
Reputation: 595402
If operator>>
fails to extract a value, it puts the input stream into an error state. You are not clearing that state, or ignoring the bad input that caused it to fail, so operator>>
keeps failing.
Try this instead:
void addItem(struct InventoryItem inventory[], int& size){
do {
cout << "Enter the item name: ";
if (cin.getline(inventory[size].itemName, MAX_CHAR, '\n')) {
if (strlen(inventory[size].itemName) > 0) {
break;
}
}
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid item name!" << endl;
}
while (true);
do {
cout << "Enter the item price: ";
if (cin >> inventory[size].itemPrice) {
if (inventory[size].itemPrice >= 0) {
break;
}
}
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid item price!" << endl;
}
while (true);
cout << endl;
size++;
}
Upvotes: 1