VS2013 中編寫 C++ 控制台程序(黑框),需實現主菜單顯示,用戶輸入選項後跳轉到對應功能界面,返回主菜單繼續操作。
Windows 控制台無原生「界面」概念,通過 清屏 + 重新繪製文本 模擬界面切換。
// ConsoleApplication.cpp
#include "stdafx.h" // VS 預編譯頭,非 VS 可刪除
#include <iostream>
#include <cstdlib> // system() 需此頭文件
using namespace std;
void showMainMenu() {
system("cls"); // 清屏
cout << "========== 主菜單 ==========" << endl;
cout << "1. Hello World" << endl;
cout << "2. How are you?" << endl;
cout << "3. 退出程序" << endl;
cout << "請輸入選項 (1-3): ";
}
void funcHello() {
system("cls");
cout << "--- 功能 1 ---" << endl;
cout << "Hello World!" << endl;
cout << "按任意鍵返回主菜單...";
cin.ignore(); cin.get(); // 等待用戶按鍵
}
void funcHowAreYou() {
system("cls");
cout << "--- 功能 2 ---" << endl;
cout << "How are you?" << endl;
cout << "按任意鍵返回主菜單...";
cin.ignore(); cin.get();
}
int main() {
int choice = 0;
while (true) {
showMainMenu();
if (!(cin >> choice)) { // 輸入非數字處理
cin.clear();
cin.ignore(numeric_limits::max(), '\n');
continue;
}
switch (choice) {
case 1: funcHello(); break;
case 2: funcHowAreYou(); break;
case 3:
cout << "感謝使用,再見!" << endl;
return 0;
default:
system("cls");
cout << "無效選項,請輸入 1-3。" << endl;
cin.ignore(); cin.get();
}
}
return 0;
}
| 函數/技術 | 作用 | 注意事項 |
|---|---|---|
system("cls") | 調用 Windows cmd 清屏命令 | 需 #include <cstdlib>;跨平台可用 ANSI 轉義序列 \033[2J\033[H |
cin.ignore(); cin.get(); | 清空緩衝區並等待回車 | 防止上次輸入殘留的換行符導致直接跳過 |
cin.clear(); cin.ignore(...) | 處理非數字輸入錯誤狀態 | 恢復流狀態並丟棄錯誤行 |
while(true) 循環 | 主程序持續運行直到選擇退出 | 配合 return 0 退出 |
clearScreen(),Windows 用 system("cls"),Linux/Mac 用 system("clear") 或 ANSI 碼。getValidInt(min, max) 簡化主邏輯。SetConsoleTextAttribute,跨平台用 ANSI 顏色碼。控制台程序「界面切換」本質是 清屏 + 重繪文本 + 循環等待輸入。掌握 system("cls")、輸入流處理、循環結構即可實現多級菜單系統。