2016-06-22 2 views
0

내 반복 루핑에서 문제가 발생합니다. 처음으로 문제에 올바르게 대답하면 프로그램을 진행할 수 있습니다. 그러나 정수를 사용하면 false로 반복됩니다. 올바르게 루프에 응답해도 종료되지 않고 문자열 값을 저장합니다. 문제는이 질문에서 사람이 정수를 입력하는 것을 원하지 않는다는 것입니다. 따라서 정수에 대한 행을 확인합니다.부울은 while 루프와 함께 작동하지 않습니다.

#include "stdafx.h" 
#include "stdio.h" 
#include <iostream> 
#include <ctime> 
#include <string> 
#include <time.h> 
#include <algorithm> 
#include "ThreeWayRace.h" 
#include <cctype> 
#include <functional> 


using namespace std; 

void Options() 
{ 

string carColor; 
int carNumber; 
int s; 
cout << "Please type a color in for your car: "; 
cin>>carColor; 
bool contains_non_alpha 
    = std::find_if(carColor.begin(), carColor.end(), 
     std::not1(std::ptr_fun((int(*)(int))std::isalpha))) != carColor.end(); 
while (contains_non_alpha == true) 
{ 

    cout << "Please enter letters only. "; 
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    cin>>carColor; 

} 
+4

'contains_non_alpha' 같은 do while 루프를 사용할 수 있습니다. 그것은 마법에 의해서만 변하지 않을 것입니다 ... – John3136

+0

부울은 절대로 변경되지 않으므로 루프가 종료되지 않습니다 – Li357

+0

이 경우에는 ['std :: all_of'] (http://en.cppreference.com/w/cpp/algorithm/all_any_none_of), 간단하게'std :: isalpha'를 술어로 전달합니다. 'std :: find_if' 대신에 말입니다. –

답변

2

코멘트가 말했듯이 당신이 실제로 contains_non_alpha의 값은 변경하지 않습니다 의미 루프에서 체크를하지 않습니다.

간단한 해결책은 임시 변수가 필요없는 루프 조건의 일부로 자체 검사를 수행하는 것입니다.

내 댓글에서와 마찬가지로 std::all_of 기능을 사용하면 다음과 같이 할 수 있습니다.

while (!std::all_of(std::begin(carColor), std::end(carColor), std::isalpha)) 
{ 
    ... 
} 

은 또한 루프 내에서 설정되지 않은이

void Options() 
{ 
    std::string carColor; 

    do 
    { 
     std::cout << "Please type a color in for your car (letters only): "; 
     std::cin >> carColor; 
    } while (!std::all_of(...)); 

    int carNumber; 
    // ... rest of code... 
} 
+0

.... 문자에 대한 문자열 값을 검사하는 방법을 알아 내려고 노력하면서 시간을 보냈을 때 나는 매우 어리 석습니다. 오직 ..... 요아킴에게 감사드립니다! –

+0

@ NathanielPetterson 어떻게 완료했는지 모든 것이 이해되면 쉽습니다. :) –

관련 문제