我正在尝试制作一个模板,这是我的课堂作业。 我在do while循环中使用了switch语句,条件是如果输入变量不等于16,则应终止程序
我已经在每种情况下都使用了中断声明,但是它不起作用
#include <iostream>
using namespace std;
int main()
{
int op;
cout << "Please enter choice between 1 to 15 For Different Operations "
<< endl;
cout << "1. Create List(create a new list(presumably empty))" << endl;
cout << "2. Insertion" << endl;
cout << "3. Deletion" << endl;
cout << "4. Update(replace the element)" << endl;
cout << "5. Start" << endl;
cout << "6. Next" << endl;
cout << "7. Back" << endl;
cout << "8. Tail" << endl;
cout << "9. Find" << endl;
cout << "10. Copy" << endl;
cout << "11. Get(display current index and element)" << endl;
cout << "12. Size / length" << endl;
cout << "13. Display list" << endl;
cout << "14. De - allocate list" << endl;
cout << "15. Exit" << endl;
cin >> op;
do {
switch (op) {
case 1:
cout << "Creating the List" << endl;
break;
case 2:
cout << "inserting... " << endl;
break;
case 3:
cout << "Deleting... " << endl;
break;
case 4:
cout << "updating... " << endl;
break;
case 5:
cout << "starting... " << endl;
break;
case 6:
cout << "next... " << endl;
break;
case 7:
cout << "back... " << endl;
break;
case 8:
cout << "Tail... " << endl;
break;
case 9:
cout << "Find... " << endl;
break;
case 10:
cout << "Copying... " << endl;
break;
case 11:
cout << "Getting... " << endl;
break;
case 12:
cout << "Size... " << endl;
break;
case 13:
cout << "Display... " << endl;
break;
case 14:
cout << "Deallocate... " << endl;
break;
case 15:
terminate;
break;
default:
cout << "Please enter the correct choice " << endl;
break;
}
} while (op != 16);
return 0;
}
我希望用户做出的每个选择中都有cout输出,然后停止输入
答案 0 :(得分:2)
使用原始代码
cin >> op;
do {
switch (op)
因此您从循环外的cin处读取,再也不会再次读取,因此重新排序以便每次循环读取时都会再次询问您所需的操作
do {
cin >> op;
switch (op)
另外请注意,break不会中断循环,而只是从开关中断。在不中断的情况下,下一种情况的指令也将在开关中执行。
如果要在某些情况下从循环中中断,则需要在switch语句之外添加一个中断,如果应该退出循环,则可以使用变量来“记住”。
但是,由于键入指令中存在退出条件,为什么不退出循环
} while (op != 15);
这似乎很合理,因为
cout << "15. Exit" << endl;
行。