c++ - 重印选项列表

标签 c++ loops for-loop while-loop break

我正在学习 c++,目前正在解决“Jumping into c++”一书中的练习题。

我当前的问题是我正在尝试创建一个列表,让用户选择一个选项,如果输入不是选项之一,它会重新打印列表。

我已经到了用户可以从其中一个选项中进行选择并且程序将继续进行的地步,但是如果用户输入不是选项之一,我将无法重新打印列表。

{
   string option;


   while (true)
    {
    cout << "Please select and option from the following:" << '\n';
    cout << "Fish" << '\n' << "Chips" << '\n' << "Peas" << '\n';
    cin >> option;
    {
        if (option == "Fish" || option == "chips" || option == "Peas")
        {
            cout << "Thank you, you have chosen " << option << '\n';
        }
        break;
        cout << "Please choose again" << '\n';
    }

  }

}

我希望你能看到我在这里想要实现的目标。我是一个 super 菜鸟,所以这真的超出了我的舒适区,但对你们中的一些人来说可能看起来很简单,哈哈。

提前感谢您的任何建议。

杰斯。

最佳答案

break; 命令退出当前循环。您当前的代码无条件地执行它,这可能不是您想要的。将其移动到由 if 控制的 block 中:

while (true)
{
  cout << "Please select and option from the following:" << '\n';
  cout << "Fish" << '\n' << "Chips" << '\n' << "Peas" << '\n';
  cin >> option;
  {
    if (option == "Fish" || option == "chips" || option == "Peas")
    {
      cout << "Thank you, you have chosen " << option << '\n';
      break;
    }
    cout << "Please choose again" << '\n';
  }
}

我还建议你摆脱嵌套的大括号 block ,它对程序执行完全没有任何作用(你甚至没有任何嵌套的变量):

while (true)
{
  cout << "Please select and option from the following:" << '\n';
  cout << "Fish" << '\n' << "Chips" << '\n' << "Peas" << '\n';
  cin >> option;
  if (option == "Fish" || option == "chips" || option == "Peas")
  {
    cout << "Thank you, you have chosen " << option << '\n';
    break;
  }
  cout << "Please choose again" << '\n';
}

诸如此类的问题通常可以通过在调试器中单步执行代码来快速解决。这是任何程序员的必备技能,您应该尽快学习。

关于c++ - 重印选项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951022/

相关文章:

c++ - stack<int, list<int>> 到底是什么意思,它与 stack<int> 有何不同?

c++ - 当我在 C++ 中获得 vector 的索引时,它总是返回最后一个被推回的值

c++ - 更新 OSX 命令行工具 6.3 后缺少 C++ header <__debug>

C# while 循环范围为 0 - 5

json - jq json对象连接到bash字符串数组

python - 组合字符串列表,提高性能

c++ - Break 在不该执行的时候执行

c++ - 如何在控制台上打印数字为0-99的简单数组

python - 为什么我的列表按数字升序返回?

python - 滚动操作性能缓慢创建新列