我的C ++程序不接受用户的输入

时间:2015-11-11 19:32:13

标签: c++ c++11 visual-c++

我的程序没有输入。

不是String的情况,我在cin运算符中遇到问题,所以我无法理解程序的输出。 请给我理由及其准确的解决方案。

struct Product
{
        int code;
        string description;
        char packaging;
        float price;
        float discount;
};

int main()
{
        Product p;

        cout << "\nEnter a code of a product:\t";
        cin >> p.code;

        cout << "\nEnter the description of a product:\t";
        getline(cin, p.description);
        cin.ignore();

        cout << "\nPress:";
        cout << "\n\t'L' or 'l' for large";
        cout << "\n\t'M' or 'm' for medium";
        cout << "\n\t'S' or 's' for small";

错误

        cout << "\n\nChoose your package from the list above:\t";
        cin >> p.packaging;

错误

   switch (p.packaging)
       {
       case 'L':
       case 'l':
                p.price = 50000;
                cout << "\nThe price of a product:\t$" << p.price;
                break;

       case 'M':
       case 'm':
                p.price = 25000;
                cout << "\nThe price of a product:\t$" << p.price;
                break;

       case 'S':
       case 's':
                p.price = 12500;
                cout << "\nThe price of a product:\t$" << p.price;
                break;

      default:
                cout << "\nYou entered wrong";
      }

      p.discount = 0.02;

      cout << "\nDISCOUNT:\t" << p.discount;

      double deductedPrice;

      deductedPrice = p.price * p.discount;

      p.price = p.price - deductedPrice;

      cout << "\nDiscounted price:\t" << p.price;



      cout << "\n\n\n\n\n";

      system("pause");

      return 0;
}

我从互联网上搜索过但我无法得到满足我的任何解决方案。

输出屏幕的快照

Output screen

1 个答案:

答案 0 :(得分:1)

问题是在std::cin >> p.code之后,流中还有一个新行,即“吃掉”#34;按getline。解决方案:在std::cin >> p.code;

之后立即添加以下行
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

忽略它(确保你在开始时#include <limits>)。