2017-11-02 71 views
-1

사용자는 double을 입력해야하지만 프로그램이 문자열이나 문자를 무시하면 어떻게 처리합니까? 현재 코드의 문제는 프로그램에 스팸 메일을 넣고 화면을 채울 때의 문제입니다. a cout < < "사각형의 길이는 얼마입니까?";사용자가 입력 한 문자열을 어떻게 무시할 수 있습니까?

double length; 

do { 
    cout << "What is the length of the rectangle: "; 
    cin >> length; 
    bString = cin.fail(); 
} while (bString == true); 
+1

'while (bString == false);'Btw, 코드에 무엇이 잘못된 것인지 말하지 않았습니다. – DimChtz

+0

@DimChtz 사용할 때 (bstring == false); –

+0

'std :: cin :: fail()'은'cin'에 대한 마지막 호출이 실패한 경우'true'를 리턴합니다. 그래서,'cin'이 실패하지 않는 한 반복하기를 원하기 때문에'while (bString == false);'가 필요합니다. – DimChtz

답변

1
do { 
    cout << "What is the length of the rectangle: "; 
    cin >> length; 
    bString = cin.fail(); 
    cin.clear(); 
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
} while (bString == true); 

이것은 내 문제의 코드입니다.

-1

사용자가 잘못된 데이터 형식을 입력하면 cin이 실패합니다. 이것을 사용하여 확인할 수 있습니다

double length; 
while(true) 
{ 
    std::cout << "What is the length of the rectangle: "; 
    std::cin >> length; 

    if (std::cin.fail()) 
    { 
     std::cout << "Invalid data type...\n"; 
     std::cin.clear(); 
     std::cin.ignore(); 
    } 
    else 
    { 
     break; 
    } 
} 
+2

'NULL'을 사용하지 마십시오. 왜 네가? – DimChtz

+0

@DimChtz 맞아, 내 솔루션을 업데이트했습니다. –

+0

해결책이 잘못되었습니다. 이것을 봐주세요. – DimChtz

0

cin.fail()은 정수와 부동 소수점을 구분하지 않습니다.

가장 좋은 방법은 std::fmod() 기능을 사용하여 알림이 0보다 큰지 확인하는 것입니다. 만약 그것이 부동 소수점이면.

여기서 코드

#include <cmath> 

int main() 
{ 
    double length; 
    std::cout <<"What is the length of the rectangle: "; 
    std::cin >> length; 

    if (std::cin.fail()) 
    { 
     std::cout<<"Wrong Input..."<<std::endl; 
    } else 
    { 
     double reminder = fmod(length, 1.0); 
     if(reminder > 0) 
      std::cout<<"Yes its a number with decimals"<<std::endl; 
     else 
      std::cout<<"Its NOT a decimal number"<<std::endl; 
    } 
} 

이 코드 (12) 및 12.0 구별하지 것을주의한다.