[c ++ for循环不会停止……循环

问题描述 投票:-2回答:2

请帮助!我开始感到绝望。

我正在尝试为菜单编写代码,该菜单会继续询问选项,直到您键入'q'退出为止。这似乎很容易,但是由于某种原因,即使“ continue”,我的if循环中只有一个拒绝停止循环。存在。我可以使它停止循环的唯一方法是使用“ break”。但随后它退出了while循环,因此我无法保持菜单打开。我尝试在for循环内外前后移动输入,以查看是否有帮助,但我尝试做的似乎无济于事。

另外,我要指出的是,ADD if循环无法正常工作。其他循环似乎运行良好。检查是否为'a'。

有人知道我在做什么错吗?我知道这一定是愚蠢的...

   do {
      cin >> input;

      if (input == ' ') {
         continue;
      }

      if (input == 'a') {
         cout << "ADD ITEM TO CART" << endl;

         cout << "Enter the item name:" << endl;
         cin >> item_name;
         cout << "Enter the item description:" << endl;
         cin >> descript;
         cout << "Enter the item price:" << endl;
         cin >> price;
         cout << "Enter the item quantity:" << endl;
         cin >> qty;

         item.SetDescription(item_name, descript, price, qty);

         cout << endl;
         cout << "Choose another option:" << endl;
         continue;
      }

      if (input == 'd') {
         cout << "REMOVE ITEM FROM CART" << endl;

         cout << "Enter name of item to remove:" << endl;
         getline(cin, item_name);

         cout << endl;
         cout << "Choose another option:" << endl;
         continue;
      }

      else if (input == 'c') {
         cout << "CHANGE ITEM QUANTITY" << endl;

         cout << "Enter the item name:" << endl;
         getline(cin, item_name);
         cout << "Enter the new quantity:" << endl;
         cin >> qty;

         descript = "none";
         price = 0.00;

         itemChange.SetDescription(item_name, descript, price, qty);
         currCustomer.ModifyItem(itemChange);

         cout << endl;
         cout << "Choose another option:" << endl;
         continue;
      }      

      else if (input == 'i') {
         currCustomer.PrintDescriptions();
         cout << endl;
         cout << "Choose another option:" << endl;
         continue;
      }      

      else if (input == 'o') {
         cout << "OUTPUT SHOPPING CART" << endl;
         currCustomer.PrintTotal();
         cout << endl;
         cout << "Choose another option:" << endl;
         continue;

      }

      else if (input == 'q') {
         continue;
      }

      else {
         cout << "Invalid option. Please try again:" << endl;
         cin >> input;
         continue;
      }

      input = ' ';

   } while (input != 'q');
c++ for-loop break continue
2个回答
0
投票

对于原始代码,在您的else语句之前,先编写一个if语句,然后再创建其他if语句。开关可以带间断使用,但要取决于首选项。

do {      cin >> input;

  if (input == ' ') {
     continue;
  }

  else if (input == 'a') { /after above if just make all others else if
     cout << "ADD ITEM TO CART" << endl;


  else if (input == 'q') {
     continue; // not an issue as you can use it for something
 input = ' '; //not really needed but no harm as it gets skipped due to continue statemnets

-1
投票

我认为您的问题与以下陈述有关:

else if (input == 'q') {
    continue;
    }

您可能想用continue替换break

continue使执行循环(再次)。

© www.soinside.com 2019 - 2024. All rights reserved.