简体   繁体   中英

C++ how to continue the main until user selection is exit selection

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;
}

Above is my partial code string userOption() is a function that print out the menu like this kind

Currency

  1. USD/SGD
  2. EUR/USD
  3. Enter your own currency pair
  4. Exit from program

How do i make main don't exit until selection is 4 from userOption

A simple 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;
}
int main()
{
    string selection;
    while( (selection = userOption()) != "4")
    {
        cout << selection << endl;
        //now perform web parser
        webparser(selection);    
        //now perform searchstring
        searchString(selection);
    }
    return 0;
}
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;
}

Similar to perreals answer. There are many ways how to write "endless" loop, and I think that expressing it in the loop header (either as this or by while(true) ) is better - when you start reading the loop, you know immediatelly that the end condition is somewhere inside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM