C++ -- Switch的基本用法

switch只能接受整型和字符型:

整型:

#include <iostream>
using namespace std;

int main(void){   
  int a;
  while(true) {
    cin >> a; 
    switch(a) {
      case 1:
        cout <<  "hi" << endl;
        break;
      case 2:
        cout << "hello" << endl;
        break;
      default:
        cout << "goodbye" << endl;
    }
  }
}

字符型:

#include <iostream>
using namespace std;

int main(void){   
  char a;
  while(true) {
    cin >> a; 
    switch(a) {
      case 'b':
        cout <<  "hi" << endl;
        break;
      case 'c':
        cout << "hello" << endl;
        break;
      default:
        cout << "goodbye" << endl;
    }
  }
}

 

posted @ 2021-03-29 13:33  手磨咖啡  阅读(1592)  评论(0编辑  收藏  举报