首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

Thinking in C++ 習題 21:單詞映射整數 + switch 處理

     編輯:C++ 入門

題目要求

從標準輸入讀取單詞,用 if-else 將單詞映射為整數,再用 switch 處理。特定單詞(如 "i", "love", "China")映射為 5,其他映射為 1。輸入 "exit" 結束。

代碼結構

class OperatorText {
    string word;
    int code;
public:
    void inWord(istream& is) { cout << "輸入單詞: "; is >> word; }
    void wordToInt() {
        if (word=="i"||word=="I"||word=="love"||word=="Love"||word=="LOVE"||word=="China")
            code = 5;
        else
            code = 1;
    }
    string theMeanOfInt() {
        switch (code) {
            case 5: return word + ": 這個單詞大寫.";
            case 1: return word + ": 這個單詞小寫.";
            default: return "未知";
        }
    }
};

int main() {
    char ch;
    while (true) {
        OperatorText ot;
        ot.inWord(cin);
        ot.wordToInt();
        cout << ot.theMeanOfInt() << endl;
        cout << "繼續? (y/n): "; cin >> ch;
        if (ch == 'n') break;
    }
    return 0;
}

關鍵點

  • 類封裝:單詞存儲、映射邏輯、輸出邏輯分離。
  • switch 處理映射後的整數,擴展性好。
  • 循環讀取直到用戶選擇退出。

總結

基礎 C++ 類設計練習:輸入處理、條件映射、switch 分支、交互循環。展示了面向對象封裝簡單邏輯的標準流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved