在while循环中执行的效果不如预期

问题描述

我正在创建俄勒冈线索克隆作为概念类型的证明,由于某种原因,我在int main之前确定的函数循环没有循环,只是没有做任何事情。

using namespace std;
int debuginput;
string response;
int loop = 0;
void commands ()
{
  if (response == "cmd")
    {
      cout <<
    "what would you like to do? type 'help' to get a list of commands." <<
    endl;
      cin >> response;
      if (response == "start")
    {
      loop = 1;
    }
      else
    {
      loop = 0;
    }
      if (response == "test")
    {
      cout << "test";
    }
    }
}

int
main ()
{
 cin >> response;
  do
    {
      commands ();
    }
  while (loop == 0);
/*-------------------------------------------------*/
}


基本上,每当我调用 commands 函数进行循环时,我都会输入一个命令,并且不会循环以让我输入另一个命令。

解决方法

commands函数中的这段代码中:

if (response == "start") {
   int loop = 1;
}

您在堆栈上创建一个带有名称循环的新变量,将其设置为1,然后立即将其销毁。您可以用此阴影全局变量loop

我认为正确的变体应该是:

if (response == "start") {
   loop = 1;
}

如果键入start,它将更新loop变量,然后do while循环将结束。如果这不是您想要的,则应更改条件:

void commands() {
    // ...
    cin >> response;
    if (response == "start") {
        loop = 1;
    } else {
        loop = 0;
    }
}

do {
    commands();
} while (loop == 1);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...