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