【C++】提醒使用者輸入數字,如何處理使用者錯誤輸入?(優秀的程式設計思想)
阿新 • • 發佈:2018-12-16
你提醒使用者一定要輸入5個數字
但是使用者故意輸入2個數字,一個其他字元,再輸入其他數字, 你該怎麼處理這樣的普遍情況?
解決辦法:
用到cin的bool特性!
#include <iostream> const int Max = 5; int main() { using namespace std; int golf[Max]; cout << "請輸入的分數:\n"; cout << "你必須輸入" << Max << "個數\n"; int i; for (i = 0; i < Max; i++) { cout << "得分#" << i + 1 << ": "; while (!(cin >> golf[i])) { cin.clear(); while (cin.get() != '\n') { continue; }//跳過錯誤輸入 cout << "請輸入一個數字:"; } } double total = 0.0; for (i = 0; i < Max; i++) { total += golf[i]; } cout << total / Max << "平均值" << Max << " 重量\n"; system("pause"); return 0; }
執行結果 如下:
核心程式碼:
while (!(cin >> golf[i]))
{
cin.clear();
while (cin.get() != '\n')
{
continue;
}//跳過錯誤輸入
cout << "請輸入一個數字:";
}