2014-10-24 3 views
-5

진술이 거짓이면 사용자 입력 값을 다시 만들기 위해 어떤 루프를 사용해야합니까? 한 달 안에 최대 31 일이 있음을 의미하므로 사용자가 32를 입력하면 프로그램에서 다시 입력하라는 메시지를 표시하고 문이 참이면 루프가 종료됩니다. 그래서 같이참 값 뒤에 나오는 루프를 만드는 방법

int main() 
{ 
    int day; 
    cout<<"Enter a day"<<endl; 
    cin>>day; 
     if(day<32){ 
    // class Input 
    Input inObject(day); 
    // printInput(){cout<<"Today is the "<<input<<endl;} 
    inObject.printInput(); 
    }else{ 
     cout<<"Incorrect day! Enter again."<<endl; 
    } 
    return 0; 
} 
+0

'에 대한 일반화 된 방법 (부울 valid_input = false를 valid_input;!의) {/ ** /}'? – moooeeeep

+1

루프를 사용하여 종료 할 값에 관계없이 종료 할 수 있습니다. –

+1

'break' 문에 대해 자세히 알아보십시오! –

답변

1

:

#include <cstdlib> 
#include <iostream> 

int main() 
{ 
    for (int day; std::cout << "Enter a day: " && std::cin >> day;) 
    { 
     if (day > 31) 
     { 
      std::cout << "Invalid day, try again.\n"; 
      continue; 
     } 

     Input inObject(day); 
     // ... 
     return EXIT_SUCCESS; 
    } 

    std::cout << "Premature end of input!\n"; 
    return EXIT_FAILURE; 
} 

당신은의 int보다는 캐릭터 라인을 읽어이를 구체화 할 수 있습니다. 정수가 아닌 코드를 입력하면 현재 코드가 완전히 실패합니다. 가능한 개선 :

for (std::string line; 
    std::cout << "Enter a day: " && std::getline(std::cin, line);) 
{ 
    std::istringstream iss(line); 
    int day; 
    if (!(iss >> day >> std::ws) || iss.get() != EOF || day > 31) 
    { 
     /*error*/ 
     continue; 
    } 

    // as before 
} 
+0

[데모] (http://ideone.com/LeRJJh), [향상된 데모] (http://ideone.com/kyc1Qf) –

+0

왜 스크롤 가능한 코드 상자의 오른쪽 테두리 뒤에 가장 중요한 문구를 숨기셨습니까? –

+0

@JanHudec : 재미있게 보려면 화면이 너비가되어야합니다. -S 죄송합니다. –

0

에 대한 문제

#include <iostream> 
#include <string> 
#include <functional> 

template<typename Ty> 
struct CheckedIn 
{ 
    CheckedIn(std::function<bool(Ty)> fn): m_fn(fn) {} 
    CheckedIn(std::string prompt, std::function<bool(Ty)> fn):m_prompt(prompt), m_fn(fn) {} 
    CheckedIn(std::string prompt, std::function<bool(Ty)> fn, std::string errormsg): 
     m_prompt(prompt), m_errormsg(errormsg), m_fn(fn) {} 
    CheckedIn& operator>>(Ty _in) 
    { 
     do 
     { 
      std::cout << m_prompt; 
      std::cin >> _in; 
     } while(m_fn(_in) && std::cout<<(m_errormsg==""?"Invalid Input":m_errormsg)); 
     return *this; 
    } 

private: 
    std::function<bool(Ty)> m_fn; 
    std::string m_prompt; 
    std::string m_errormsg; 
}; 

int main() 
{ 
    int day = int(); 
    CheckedIn<int>("Enter a day: ", 
        [](int day){return bool(day > 31); }, 
        "Invalid day, try again.\n") >> day; 
    return 0; 
} 
+0

이 코드는 [I/O 작업 결과를 무시하므로] 위험 할 정도로 손상되었습니다 (http://stackoverflow.com/a/26557243/596781). –

+0

그리고 이것을 실제로 테스트 해 보셨습니까? –

관련 문제