2016-06-22 5 views
0

私のwhileループではサイクルが壊れています。初めて問題に正しく答えると、プログラムを進めることができます。しかし、私は整数を使用する場合、それはループで正しく答えるとしても、それは終了せず、文字列の値を保存します。問題は、私がこの質問で整数を入力することを望まないということです。だから、整数の行をチェックします。あなたが実際にcontains_non_alphaの値が変化することはありません意味し、ループのチェックをしないコメントで言われたようブールループは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

単純な解決策は、ループの条件の一部としてチェック自体を行うことです。一時変数は必要ありません。

私のコメントのように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どのように完了したら、すべてが簡単です。 :) –

関連する問題