我試圖獲得一串運行在一起的字符,以便對一組「有效」字符進行解析。如果字符串全部是「有效」集合中的一個,則代碼應該繼續。如果字符串包含除有效集之外的任何字符,則應返回錯誤並提示重新輸入,並再次檢查其是否有效。將字符串與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
非常感謝!奇蹟般有效。 – user2856303