2014-10-29 3 views
0

사용자 입력의 유효성을 검사하고 입력이 잘못된 경우 반복되는 루프를 작성하려고합니다. 입력은 이진수 (문자열) 또는 십진수 (int) 여야합니다. 이 입력을 검증하기 위해 별도의 함수가 있지만 문제가 발생하지는 않습니다.실수로 사용자 입력을 건너 뜁니다.

1 또는 2를 선택한 다음 잘못된 2 진 또는 10 진수를 기꺼이 입력하면 문제가 발생합니다. 이 시점에서 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; 

} 

답변

2

오히려 현재의 프로그램을 디버깅보다 당신은 당신이 충분히 쉽게 다시에 다시 추가 할 수 있어야 루프이 원하는 경우 단순히 일

#include <iostream> 
#include <string> 
#include <bitset> 
#include <climits> 
#include <limits> 

template<typename T> 
void get(T& value) 
{ 
    while (!(std::cin >> value)) { 
    std::cout << "Invalid input\n"; 
    std::cin.clear(); 
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 
} 

int main() 
{ 
    std::cout << "Enter 1 to convert binary to decimal,\n" << 
       "2 to convert decimal to binary\n"; 

    int option; 

    if (std::cin >> option) { 
    switch (option) { 
     case 1: { 
     std::bitset<CHAR_BIT * sizeof(unsigned long long)> bits; 
     get(bits); 
     std::cout << bits.to_ullong() << '\n'; 
     break; 
     } 

     case 2: { 
     unsigned long long i; 
     get(i); 
     std::cout << std::bitset<CHAR_BIT * sizeof i>(i) << '\n'; 
     break; 
     } 
    } 
    } 
} 

에 표준 라이브러리를 사용하여 고려할 수 있습니다 .

+0

감사합니다. 그러나이 과제에 대해 우리는 변환 기능을 사용하거나 다른 선택 기능을 사용해서는 안됩니다. – FluffyKittens

+0

@AdamJ 그런 경우 입력 오류 처리를 위의 일반 논리를 계속 사용할 수 있습니다. 다음 번에 과제 일 경우 질문에서 사용할 수있는 것과 사용할 수없는 것을 분명히하십시오. – user657267

+0

도움을 주시면 감사하겠습니다 만, 루프가 반복 될 때 코드가 cin의 값을 읽지 못하는 이유에 대한 답을 찾고 있습니다. 과제를 경쟁하는 것뿐만 아니라 내 자신의 학습 목적을 알고 싶습니다. – FluffyKittens

관련 문제