0
我想寫一個循環來驗證用戶輸入,然後重複輸入是壞的。輸入必須是二進制數(作爲字符串)或十進制數(作爲int)。我有單獨的函數來驗證這個輸入,但它們不會造成任何麻煩。cin無意中跳過用戶輸入
當我選擇1或2,然後甘願輸入一個無效的二進制或十進制數時,就會出現問題。此時,do-while循環成功重複。該程序將用戶輸入的另一個請求打印到cout
,但是當用戶輸入輸入時,程序認爲在輸入任何內容之前控制檯中都有輸入。我相信這是緩衝區中whitespace/control
個字符的問題,但我不確定如何解決它。我曾嘗試使用std::cin >> std::ws
來清除任何離散的白色空間,但沒有運氣。
#include <iostream>
#include <string>
#include <limits>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::max;
using std::streamsize;
using std::string;
//int toDecimal;
//true is is binary
bool validateBinary(const string &binaryNumber){
for(int i = 0; i < binaryNumber.length(); i++){
if((binaryNumber[i] != 1) && (binaryNumber[i] != 0)){
return false;
}
}
return true;
}
//true if is decimal
bool validateDecimal(){
return cin;
}
int main() {
int conversionType = 0; //we initialize conversionType to a default value of 0 to ensure the copiler it will always have a value
bool isBinary = false;
bool isDecimal = false;
string binaryNumberInput;
int decimalNumberInput;
do {
if(conversionType == 0){
cout << "Enter 1 to convert binary to decimal," << endl;
cout << "2 to convert decimal to binary, " << endl;
cout << "or 3 to exit the program: ";
std::cin >> std::ws; //to clear any whitespace fron cin
cin >> conversionType; //upon a second iteration, this value is read in before a user input is given
}
if(!cin || (conversionType != 1 && conversionType != 2)){
cout << "Incorrect input." << endl;
cin.clear(); //clear the fail bit
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //used to ignore not-numeric input
}
cout << "You have selected option " << conversionType << "." << endl;
if(conversionType == 1){
cout << "Please enter a binary number: ";
cin >> binaryNumberInput;
isBinary = validateBinary(binaryNumberInput);
if(!isBinary){
cout << "The numbered you entered is not a binary number!" << endl;
conversionType = 0;
}
}
if(conversionType == 2){
cout << "Please enter a decimal number: ";
cin >> decimalNumberInput;
isDecimal = validateDecimal(); //true if succeeded, meaning is a number
if(!isDecimal){
cout << "The numbered you entered is not a decimal number!" << endl;
conversionType = 0;
}
}
}
while((conversionType != 1 && conversionType != 2) || (isBinary == isDecimal));
return 0;
}
謝謝,但對於這項任務,我們不允許使用任何轉換函數,否則這將是我的第一選擇。 – FluffyKittens 2014-10-29 04:15:19
@AdamJ在這種情況下,您仍然可以使用上面的通用邏輯來處理輸入錯誤。另外,下一次清楚說明,如果這是一項任務,您可以在問題中不能使用什麼。 – user657267 2014-10-29 04:16:23
我很感激這個幫助,但我真的只是在尋找答案,爲什麼我的代碼在循環重複時拒絕從cin讀取值。我想知道我自己的學習目的,而不僅僅是爲了爭奪任務。 – FluffyKittens 2014-10-29 04:32:21