简体   繁体   中英

End a while loop that continue ask for string input until I enter -1

I have to create a menu that holds item names, I can do it with a for loop that ends until the max has been reach, but how do I do it with a while loop that will continue ask until the max is reached or I enter -1

I tried with a for loop and it worked, but I have to use a while loop that can stop when I tell it to stop.

#include <iostream>

using namespace std;

void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
                  int MAX_MENU_ITEMS);

int main()
{
    const int MAX_MENU_ITEMS = 5;
    char menu_list[MAX_MENU_ITEMS][50];
    float price_list[MAX_MENU_ITEMS];
    int num_menu_items;

    read_in_menu(menu_list, price_list, num_menu_item, MAX_MENU_ITEMS);
}

void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
                  int MAX_MENU_ITEMS)
{
    for (int i = 0; i < MAX_MENU_ITEMS; i++)
    {
        cout << "Enter Names: ";
        cin.getline(menu_list[i], 20);
    }
}

I want to use a while loop that will continue going until I input -1 or reach the maximum. I want to stop the while loop whenever I want instead of the for loop where I have to reach the max.

Whenever you want to exit a loop you can use the break keyword.

for(int i = 0; i < MAX; i++){
    if(i > 10){
        break;
    }
    doWork();
}

You can transform for loop to other loops. For example:

For

for(int i = 0; i < 10; i++)
    DoSomething();

While

int i = 0;
while(i < 10){
    DoSomething();
    i++;
}

do-while

int i = 0;
do{
    DoSomething();
    i++;
}
while(i < 10);

To control the loops use continue and break keywords. Keyword continue will skip the current iteration of the loop and break will exit the loop. These are usually conditioned by if statement.

If I understand correctly, something like this should work:

int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS || input == "-1") {
    cout << "Enter Names: ";
    cin.getline(input, 20);
    if(input != "-1") { //to avoid setting menu_list[i] = "-1"
        menu_list[i] = input;
    }
    MAX_MENU_ITEMS++;
}

or using break:

int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS) {
    cout << "Enter Names: ";
    cin.getline(input, 20);
    if(input == "-1") { 
        break;
    }
    menu_list[i] = input;
    MAX_MENU_ITEMS++;
}

I was able to get it with a pointer lol.

void read_in_menu(char menu_list[5][20], float price_list[], int &num_menu_items, int MAX_MENU_ITEMS){
int i = 0;
char *p = "-1";
while(i<MAX_MENU_ITEMS){
cout << "Enter Name" << endl;
cin.getline(menu_list[i],20);
if(strcmp(menu_list[i], p)){
i++;
}else{
break;
}
}
}

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