2013-10-08 316 views
1

我試圖獲得一串運行在一起的字符,以便對一組「有效」字符進行解析。如果字符串全部是「有效」集合中的一個,則代碼應該繼續。如果字符串包含除有效集之外的任何字符,則應返回錯誤並提示重新輸入,並再次檢查其是否有效。將字符串與C++中的一組字符進行比較

我想出了兩套不同的代碼來執行檢查,其中「guess」是輸入字符串,A,a,B,b,C,c,D和d是允許的字符。第一組代碼似乎第一次正確運行,然後接受任何內容,第二組代碼在進入循環後只接受一個有效的字母輸入。看過之後,似乎問題根植於邏輯陳述中。無論如何,任何援助將不勝感激。

代碼#1:

int main(){ 
using namespace std; 
string guess; 

cout << "please enter your multiple choice answers: "; 
cin >> guess; 

bool nogood = true; 
int i = 0; 
while (nogood==true){ 
if (guess[i]== ('A'||'a'||'B'||'b'||'C'||'c'||'D'||'d')){ 
    i++; 
} 
else{ 
    cout << "That is not a valid choice please try again: "; 
    cin.clear(); 
    cin >> guess; 
    i=0; 
} 

if (i=guess.length()-1){ 
    nogood = false; 
} 
else{ 
    nogood = true; 
} 

} 
...code goes on 

代碼#2:

int main(){ 
using namespace std; 
string guess; 

cout << "please enter your multiple choice answers: "; 
cin >> guess; 

for (int i =0; i < guess.length(); i++){ 
    if (guess[i] == ('A'||'a'||'B'||'b'||'C'||'c'||'D'||'d')){ 
    } 
    else{ 
     cout << "That is not a valid choice please try again: "; 
     cin.clear(); 
     cin >> guess; 
     i=0; 
    } 
} 
...code goes on 

回答

5

邏輯語句被分解,應該讀

if (guess[i] == 'A' || guess[i] == 'a' || 
    guess[i] == 'B' || guess[i] == 'b' || 
    guess[i] == 'C' || guess[i] == 'c' || 
    guess[i] == 'D' || guess[i] == 'd')){ 
} 

否則編譯器第一「計算」的單一值'A'||'a'||'B'||'b'||'C'||'c'||'D'||'d'(其等同於true)並比較guess[i]true這是這種情況下意味着true是轉換爲1

而且,在你的第一個代碼示例使用

if (i=guess.length()-1) 

但這分配i,而不是比較吧。你需要==,而不是=

if (i==guess.length()-1) 

最後,可以簡化使用std::string::find_first_not_of()整個測試

cout << "please enter your multiple choice answers: "; 
cin >> guess; 

while(guess.find_first_not_of("AaBbCcDd") != std::string::npos) { 
    cout << "That is not a valid choice please try again: "; 
    cin.clear(); 
    cin >> guess; 
} 
+0

非常感謝!奇蹟般有效。 – user2856303

1

使用std::string::find_first_ofstd::strchr

const std::string validChars = "AaBbCcDd"; 
if (validChars.find_first_of(guess[i]) != std::string::npos) { 
    // whatever 
} 

或者:

if (std::strchr("AaBbCcDd", guess[i])) { 
    // whatever 
} 
相關問題