I've been working on a shopping cart assignment lately and couldn't understand why would this code below not work.
I have to write a code that will output name, cost and quantity of items, for three items without using arrays.
At the end of the maximum of three items I have to display out the total cost of the items. Currently I'm stuck because after I add in a second item, it appears that the program does not ask for the first input (Item name). Here's the code:
#include <iostream>
int main() {
int total;
std::cout << "Item name:";
std::string itemName;
std::getline(std::cin,itemName);
std::cout << "Cost(in cents):";
int cost;
std::cin >> cost;
std::cout << "Quantity:";
int quantity;
std::cin >> quantity;
std::cout << "Do you want to add more items? (Y/N)";
char option;
std::cin >> option;
if (option == 'y') {
std::cout << "Item name:";
std::string itemName2;
std::getline(std::cin,itemName2);
std::cout << "Cost(in cents):";
int cost2;
std::cin >> cost2;
std::cout << "Quantity:";
int quantity2;
std::cin >> quantity2;
std::cout << "Do you want to add more items? (Y/N)";
char option2;
std::cin >> option2;
if (option2 == 'y') {
std::cout << "Item name:";
std::string itemName3;
std::getline(std::cin,itemName3);
std::cout << "Cost(in cents):";
int cost3;
std::cin >> cost3;
std::cout << "Quantity:";
int quantity3;
std::cin >> quantity3;
total = cost*quantity + cost2*quantity2 + cost3*quantity3;
std::cout << "Total value:" << total;
}
else {
total = cost*quantity + cost2*quantity2;
std::cout << "Total value:" << total;
}
}
else {
total = cost*quantity;
std::cout << "Total value:" << total;
}
return 0;
}
After I input 'y' after every item input, the code would somehow skip my input for itemName and output the 'Cost(in cents):' together with 'Item name:' in the same line.
I do think that it's got something to do with the getline() function, but I do not know exactly what. Any help is greatly appreciated.