我希望写出的程序在点一次菜后就结束,但在输入无效字母后继续让用户输入,直到输入一个有效字母。
(1)这是第一次写的程序
#include<iostream>
using namespace std;
int main()
{
cout << "please enter one of the following choices:\nc) carnivore p) pianist\nt) tree g)game\n";
char ch;
while (1)
{
cin >> ch;
switch(ch)
{
case 'c':cout << "a maple is a conrivore.\n"; break;
case 'p':cout << "a maple is a pianist.\n"; break;
case 't':cout << "a maple is a tree.\n"; break;
case 'g':cout << "a maple is a game.\n"; break;
default:cout << "please enter a c, p, t or g:"; break;
}
}
return 0;
}
这是运行结果。
但是点一次菜后不会退出程序。
(2)在switch后加上了break,希望输入有效字母后程序跳出switch,执行最后一个break
#include<iostream>
using namespace std;
int main()
{
cout << "please enter one of the following choices:\nc) carnivore p) pianist\nt) tree g)game\n";
char ch;
while (1)
{
cin >> ch;
switch(ch)
{
case 'c':cout << "a maple is a conrivore.\n"; break;
case 'p':cout << "a maple is a pianist.\n"; break;
case 't':cout << "a maple is a tree.\n"; break;
case 'g':cout << "a maple is a game.\n"; break;
default:cout << "please enter a c, p, t or g:"; break;
}
break; //在switch选择后加上了break
}
return 0;
}
但是这样会导致输入无效字母后也退出程序
(3)想到break和continue的关系后,把default后的break改成 先读取下一个书然后再一次进行switch判断
#include<iostream>
using namespace std;
int main()
{
cout << "please enter one of the following choices:\nc) carnivore p) pianist\nt) tree g)game\n";
char ch;
while (1)
{
cin >> ch;
switch (ch)
{
case 'c':cout << "a maple is a conrivore.\n"; break;
case 'p':cout << "a maple is a pianist.\n"; break;
case 't':cout << "a maple is a tree.\n"; break;
case 'g':cout << "a maple is a game.\n"; break;
default:
{
cout << "please enter a c, p, t or g:";
cin >> ch;
continue;
}
}
break;
}
return 0;
}
运行后发现continue退出的是外侧while循环,并且再进入while,又一次读入一个字母。此时执行default后要输入两个字母,且实际上只有第二个字母起作用。
( 这个时候感觉和目标离的很近了(≧▽≦) )
(4)最后一次,删去了default中的cin
#include<iostream>
using namespace std;
int main()
{
cout << "please enter one of the following choices:\nc) carnivore p) pianist\nt) tree g)game\n";
char ch;
while (1)
{
cin >> ch;
switch (ch)
{
case 'c':cout << "a maple is a conrivore.\n"; break;//1
case 'p':cout << "a maple is a pianist.\n"; break;//2
case 't':cout << "a maple is a tree.\n"; break;//3
case 'g':cout << "a maple is a game.\n"; break;//4
default:
{
cout << "please enter a c, p, t or g:";
continue;
}
}
break;//5
}
return 0;
}
此时前四个break都是跳出switch,第五个break是跳出while循环
而switch中conotinue对switch无效,continue只是跳出while循环的
后来又在CSDN里查了下,发现在switch有外部循环时,continue才会跳出外部循环,否则continue与break同效
我试了下,在VS2022,在没有外部循环的情况下,不能在switch里使用continue,也就是continue与break不等效。