C++编程思想 第1卷 第3章 break和continue语句

switch根据整形表达式来选择要执行的语句
选择器 selector 是一个产生整数值的表达式
如果选择器的值和 其中一个语句的整数值匹配的话就执行。
都不匹配,执行switch语句
break语句可以跳转到switch语句体的结束处
如果没有break,会按顺序执行后面的语句
switch语句可以实现多路选择,但需要求整数值的选择器。

字符串的选择器,switch是不可用的。要使用字符串选择器,用if语句


//: C03:Menu2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// A menu using a switch statement
#include <iostream>
using namespace std;

int main() {
  bool quit = false;  // Flag for quitting
  while(quit == false) {
    cout << "Select a, b, c or q to quit: ";
    char response;
    cin >> response;
    switch(response) {
      case 'a' : cout << "you chose 'a'" << endl;
                 break;
      case 'b' : cout << "you chose 'b'" << endl;
                 break;
      case 'c' : cout << "you chose 'c'" << endl;
                 break;
      case 'q' : cout << "quitting menu" << endl;
                 quit = true;
                 break;
      default  : cout << "Please use a,b,c or q!"
                 << endl;
    }
  }
} ///:~


quit = true;
quit是布尔型,值为true false 
quit为false退出循环


输出
输入q 时候退出

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80575749