而循环不';不要等待方法完成 所以我在C++中做了一段时间,但是我的while循环中有一个非常奇怪的行为。它的设计允许用户执行无限多的命令,并通过字符串的内容确定要执行的命令

而循环不';不要等待方法完成 所以我在C++中做了一段时间,但是我的while循环中有一个非常奇怪的行为。它的设计允许用户执行无限多的命令,并通过字符串的内容确定要执行的命令,c++,C++,以下是感兴趣的代码: string run; size_t found; bool understood; while (true) { run = ""; found = string::npos; cout << "Please enter command(s)" << endl; cout << "\> ";

以下是感兴趣的代码:

    string run;
    size_t found;
    bool understood;
    while (true)
    {
          run = "";
          found = string::npos;
          cout << "Please enter command(s)" << endl;
          cout << "\> ";
          cin >> run;
          found = run.find("convert");
          cout << found << endl;
          understood = false;
          if (found != string::npos) 
          {
                  cout << "Converting DNA" << endl;
                  understood = true;
                  convert();
          }
          found = run.find("purify");
          if (found != string::npos)
          {
                  cout << "Purifying DNA" << endl;
                  purify();
                  understood = true;
          }
          found = run.find("build");
          if (found != string::npos)
          {
                  cout << "Building overlaps" << endl;
                  buildOverlaps();
                  understood = true;
          }
          found = run.find("close");
          if (found != string::npos)
          {
                    cout << "Goodbye" << endl;
                    break;
          }
          if (understood == false) cout << "I'm sorry, I didn't understand you" << endl;
    }
因此,基本上,它似乎接收字符串,跳过if块(最后一个除外),然后回卷并执行适当的方法。这一切都有效,所以这只是一个小麻烦,但我想了解的行为


这些数字是找到的字符串索引的调试输出,在非测试执行中不存在。

您应该包括一个
continue在每个
if(found!=string::npos)
块的末尾

这样,如果它执行该块,它将跳过其他if块,并在执行循环时重新启动

如果您的输入是

> run converter
然后是你获取信息的方式

cin >> run;
不适用于您(
operator>
在空白处中断)。它第一次通过循环时,将尝试查找“run”字符串,然后再次尝试查找“converter”字符串。如果你想处理整条线路,你应该这样做

std::getline(std::cin, run);

runconverter
是您的输入吗?您是否希望通过调用
cin>>run
获得整个字符串“runconverter”?流提取操作符(
如果他想运行多个命令,在每个条件块的末尾添加
continue
将不允许这样做。我以前在那里有一个continue,但是你不能运行多个命令sesome,changed cin>>run to getline(cin,run),它工作得很好
std::getline(std::cin, run);