我需要创建一个程序,将价格添加到正在运行的总计中,并在您准备结账时为您提供结束总计。
我编写了一个程序,可以完成总计,但我认为在我的循环中搞砸了它,并且在您选择不想签出后跳过某些cin.get实例。
我也希望合并"按q退出"而不是"你想看看"但我正在努力,不要指望问题。
关于我如何修复代码的任何想法,以便它不会跳过我的输入命令?
#include <iomanip>
#include <iostream>
using namespace std;
const int MAXCHAR = 101;
int main()
{
double itemPrice = 0;
double totalPrice = 0;
char itemName[MAXCHAR];
char confirm;
char checkoutConfirm;
char reply;
bool checkout = false;
while (checkout == false)
{
cout << "Enter Item Name(100 characters or less): ";
cin.get(itemName, MAXCHAR, '\n');
cin.ignore(100, '\n');
cout << "Enter Item Price: ";
cin >> itemPrice;
while(!cin)
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid Input. Enter Item Price: \n\n";
cin >> itemPrice;
}
cout << "Your entry:" << endl;
cout << itemName << " - $" << itemPrice << "\n";
cout << "Correct?(y/n): ";
cin >> confirm;
if (confirm == 'y' || confirm == 'Y')
{
totalPrice += itemPrice;
cout << "Your total is: " << totalPrice;
cout << "Would you like to check out?(y/n): ";
cin >> checkoutConfirm;
if (checkoutConfirm == 'y' || checkoutConfirm == 'Y')
checkout = true;
else if (checkoutConfirm == 'n' || checkoutConfirm == 'N')
checkout = false;
else
{
cout << "Invalid Input. Enter y to checkout or n to keep shopping: ";
cin >> checkoutConfirm;
}
}
else if (confirm == 'n' || confirm == 'N')
{
cout << "Entry deleted -- Enter new information: \n";
}
else
{
cout << "Invalid Input. Enter y to checkout or n to keep shopping: ";
cin >> confirm;
}
}
return 0;
}
答案 0 :(得分:1)
在再次使用之前清除输入流缓冲区:
std::cin >> x;
std::cin.ignore();
std::cin.clear();
http://www.cplusplus.com/reference/istream/istream/ignore/ http://www.cplusplus.com/reference/ios/ios/clear/
否则您的输入可能会保留在缓冲区中并将再次使用。据我所知,你有时已经这样做了,虽然你经常忘记它。
此外,您可以查看有关退出程序的this问题。