c++ - while循环if和else

标签 c++ if-statement while-loop

代码的作用是询问用户他想要哪张卡,并根据选择的卡打印出一条声明。

我的目的是如果输入的数字不是1,2和3,则返回卡选择功能。

还有一个for循环,使该过程可以进行多次。

最好的方法是什么,我该怎么做?

int CardSelect() {

  cout << "Enter 1 for hearts" << endl;
  cout << " " << endl;
  cout << "Enter 2 for diamonds" << endl;
  cout << " " << endl;
  cout << "Enter 3 for joker" << endl;

  return 0;
};

int main() {
  for (int i = 1; i <= 5; i++) {
    CardSelect();
    int cardchoice;
    cin >> cardchoice;

    cardchoice = CardSelect();

    if (cardchoice == 1) {
      cout << "You got hearts" << endl;
      loop = false;
    } else if (cardchoice == 2) {
      cout << "You got diamonds" << endl;
      loop = false;
    } else if (cardchoice == 3) {
      cout << "You got joker" << endl;
      loop = false;
    } else {
      cout << "Invalid choice" << endl;
      cout << "Please ensure you type in the right numbers" << endl;
    }
  }
}

最佳答案

CardSelect()的返回类型更改为void,因为您只需在该函数中打印一些语句即可:

void CardSelect() 
{ // Your cout statements
}

main()中调用它,并为cardchoice变量使用开关大小写。

如果要一直运行switch语句直到获得有效的输入,请将所有内容放入inifinte循环(例如while(1))中,并通过将boolean设置为true(最初将其设置为false)并在以下情况下使用break来设置退出条件条件是令人满意的,以摆脱循环:

int main() 
{
  while(1)
  {
    bool valid = false;
    CardSelect(); // call to your function
    int cardchoice;
    cin >> cardchoice;

    switch(cardchoice)
    {
      case 1:      
      cout << "You got hearts" << endl;
      valid = true;
      break;

      case 2:     
      cout << "You got diamonds" << endl;
      valid = true;
      break;

      case 3:    
      cout << "You got joker" << endl;
      valid = true;
      break;

      default:
      cout << "Invalid choice" << endl;
      cout << "Please ensure you type in the right numbers" << endl;
      break;
    } if(valid) break;
  }
}

关于c++ - while循环if和else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233990/

相关文章:

c++ - std::chrono::high_resolution_clock - 时间测量

c++ - 检查一个线程是否完成发送另一个参数给它

if-statement - 需要帮助将命令组合到脚本中以在 Ubuntu 中运行

javascript - 缩短 if else 语句

c - 数组指针 while 循环输入

c++ - 将 QPushButton 宽度链接到另一个 QPushButton

PHP & MySql 检查表是否为空

c++ - C++ 中对象的循环问题

javascript - 退出循环内调用的回调函数

c++ - Boost日志选择目标文件