【问题标题】:C++ how to continue the main until user selection is exit selectionC ++如何继续主直到用户选择退出选择
【发布时间】:2012-07-25 06:14:56
【问题描述】:
int main()
{
    string selection;
    // print out selection menu
    selection = userOption();
    cout << selection << endl;

    //now perform web parser
    webparser(selection);    

    //now perform searchstring
    searchString(selection);
return 0;
}

以上是我的部分代码 string userOption() 就是这样打印菜单的函数

货币

  1. 美元/新加坡元
  2. 欧元/美元
  3. 输入您自己的货币对
  4. 退出程序

如何让 main 在 userOption 中选择 4 之前不退出

【问题讨论】:

标签: c++


【解决方案1】:

一个简单的do-while:

int main()
{
  string exitstr("4");
  string selection;
  do {
    // print out selection menu
    selection = userOption();
    cout << selection << endl;
    if (selection == exitstr)
      break;
    //now perform web parser
    webparser(selection);    

    //now perform searchstring
    searchString(selection);
  } while (1);
return 0;
}

【讨论】:

    【解决方案2】:
    int main()
    {
        for (;;)
        {
            string selection;
            // print out selection menu
            selection = userOption();
            cout << selection << endl;
    
            if (selection == "4") break;
    
            //now perform web parser
            webparser(selection);    
    
            //now perform searchstring
            searchString(selection);
        }
        return 0;
    }
    

    类似于 perreals 的答案。有很多方法可以编写“无尽”循环,我认为在循环头中表达它(无论是这样还是 while(true) )更好 - 当你开始阅读循环时,你立即知道结束条件是里面的某个地方。

    【讨论】:

      【解决方案3】:
      int main()
      {
          string selection;
          while( (selection = userOption()) != "4")
          {
              cout << selection << endl;
              //now perform web parser
              webparser(selection);    
              //now perform searchstring
              searchString(selection);
          }
          return 0;
      }
      

      【讨论】:

      • 如何加载新的用户输入?
      • "选择 = userOption();"应该在循环内
      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多