gpt4 book ai didi

c++ - 如何循环这个程序

转载 作者:行者123 更新时间:2023-11-27 22:58:13 24 4
gpt4 key购买 nike

所以我使用我在 YouTube 上关注的教程制作了这个简单的程序,但我没有看到的是如何让用户有机会提供新的选择,如果以前的选择无效。

程序如下:

#include <iostream>

using namespace std;

int main() {

cout << "1. Search" << endl;
cout << "2. Quit This Program" << endl;
cout << "3. View Record" << endl;

cout << "Enter Your Selection Please > " << flush;

int input;
cin >> input;

switch(input) {
case 1:
cout << "Searching..." << endl;
break;

case 2:
cout << "Quitting This Program" << endl;
break;

case 3:
cout << "Searching For Record For Viewing..." << endl;
break;
default:
cout << "That is not a valid option" << endl;
cout << "Please choose a selection from the menu:" << endl;
}

return 0;


}

最佳答案

需要一个循环来检查选择是否有效,如果有效则跳出循环,如果无效则继续循环直到有效。

#include <iostream>

using namespace std;

int main() {
bool selection = false;
while(!selection){
cout << "1. Search" << endl;
cout << "2. Quit This Program" << endl;
cout << "3. View Record" << endl;

cout << "Enter Your Selection Please > " << flush;


int input;
cin >> input;

switch(input) {
case 1:
cout << "Searching..." << endl;
selection = true;
break;

case 2:
cout << "Quitting This Program" << endl;
selection = true;
break;

case 3:
cout << "Searching For Record For Viewing..." << endl;
selection = true;
break;
default:
cout << "That is not a valid option" << endl;
cout << "Please choose a selection from the menu:" << endl;
}
}

return 0;


}

关于c++ - 如何循环这个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com