2012-11-28 49 views
-1

嘿,我試圖驗證一個字符,以限制它對男性或女性的m或f進行校正。但即使在m或f被按下的情況下它也不會通過while條件,並且不斷循環這個問題。Char驗證器不僅會接受大寫和小寫M/F

任何人可以幫助我。 在此先感謝。 這裏是我的代碼:

char Validator :: getChar(string q) 
{ 
    char input; 
    do 
    { 
     cout << q.c_str() << endl; 
     cin >> input; 
    } 
    while(!isalpha(input) && "M"||"F"||"m"||"f"); 
    return input; 
} 

回答

2

"M"||"F"||"m"||"f"你的代碼的一部分不會做你認爲它的作用。它所做的是檢查這些字符串常量的地址。由於它們都是非NULL,因此此表達式僅返回true,因此您的條件本質上變爲:while(!isalpha(input) && true),與while(!isalpha(input))相同。

試試這個:

char Validator::getChar(const string &q) 
{ 
    char input = 0; 

    do 
    { 
     cout << q << endl; 
     cin >> input; 
    } 
    while((input != 'M') && (input != 'F') && (input != 'm') && (input != 'f')); 

    return input; 
} 
+0

,完美的工作非常感謝。而你的權利我認爲會有效果,而且從現在開始我會有所不同。 – Pendo826

1

while的表達並不意味着你認爲它。首先,!不適用於整個表達式,第二,「等於」不是隱含測試。你需要寫出你的意思。

要測試其是否相等,請使用==!=運算符。您必須使用上的運算符,每個值都要測試;運營商不會像普通英語那樣「分發」價值清單。這樣寫下你的情況:

while (input != 'M' && input != 'F' && input != 'm' && input != 'f'); 

你可以看到isalpha調用是不必要的;如果input不等於任何列出的值,那麼它是否是字母字符並不重要。

另一種方式把它寫的是:

while (!(input == 'M' || input == 'F' || input == 'm' || input == 'f')); 

注意,我另一組圍繞內部條件括號,使得!操作適用於整個表達式,而不只是第一項。

1

只是爲了一種替代的方法來終止條件:

char Validator::getChar(const string &q) 
{ 
    const std::set<char> valid_chars { 'M', 'm', 'F', 'f' }; 
    char input = 0; 

    do 
    { 
     cout << q << endl; 
     cin >> input; 
    } 
    while (!valid_chars.count(q)); 

    return input; 
}