[英]End a while loop that continue ask for string input until I enter -1
我必須創建一個包含項目名稱的菜單,我可以使用for循環結束直到達到最大值,但是如何使用while循環繼續詢問,直到達到最大值或我輸入-1
我嘗試使用for循環並且它工作,但我必須使用while循環,當我告訴它停止時可以停止。
#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);
}
}
我想使用while循環,直到我輸入-1或達到最大值。 我想在我想要的時候停止while循環而不是for循環,我必須達到最大值。
無論何時想要退出循環,都可以使用break
關鍵字。
for(int i = 0; i < MAX; i++){
if(i > 10){
break;
}
doWork();
}
您可以將循環轉換for
其他循環。 例如:
對於
for(int i = 0; i < 10; i++)
DoSomething();
而
int i = 0;
while(i < 10){
DoSomething();
i++;
}
這樣做,而
int i = 0;
do{
DoSomething();
i++;
}
while(i < 10);
要控制循環,請使用continue
和break
關鍵字。 關鍵字continue
將跳過循環的當前迭代, break
將退出循環。 這些通常以if
語句為條件。
如果我理解正確,這樣的事情應該有效:
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++;
}
或使用休息:
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++;
}
我能用指針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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.