從標準輸入讀取單詞,用 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 分支、交互循環。展示了面向對象封裝簡單邏輯的標準流程。