比较break语句与continue语句的不同用法。
break;用法
break使程序从循环体和switch语句内跳出,继续执行逻辑上的下一条语句,不能用在别处;
例:
# include <iostream>
# include <cstdlib>
using namespace std;
int main()
{
char choice;
while (1)
{
cout << "Menu:A(dd)D(elete)S(ort)Q(uit),Select one:";
cin >> choice;
switch (toupper(choice))
{
case 'A':
cout << "数据已经增加." << endl;
break;
case 'D':
cout << "数据已经删除." << endl;
break;
case 'S':
cout << "数据已经排序." << endl; break;
case 'Q':
exit(0);
break;
default:
;
}
}
return 0;
}
continue;用法
continue 语句结束本次循环,接着开始判断决定是否继续执行下一次循环。
例:
# include <iostream>
# include <cstdlib>
using namespace std;
int main()
{
char choice, c;
while (1)
{
cout << "Menu:A(dd)D(elete)S(ort)Q(uit),Select one:";
cin >> c;
choice = toupper(c);
if (choice == 'A')
{
cout << "数据已经增加." << endl;
continue;
}
else if (choice == 'D')
{
cout << "数据已经删除." << endl;
continue;
}
else if (choice == 'S')
{
cout << "数据已经排序." << endl;
continue;
}
else if (choice == 'Q')
break;
}
return 0;
}
例题选自《C++语言程序设计(第四版)》
文档供本人学习笔记使用,仅供参考。