我正在尝试获取一串运行在一起的字符,以便对一组“有效”字符进行解析。如果字符串都是“有效”集的字符串,则代码应继续。但是,如果字符串包含除有效集之外的任何字符,则应返回错误并提示重新输入,再次检查其是否有效。
我提出了两组不同的代码来执行检查,其中“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
答案 0 :(得分: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}}转换为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;
}
答案 1 :(得分:1)
使用std::string::find_first_of或std::strchr:
const std::string validChars = "AaBbCcDd";
if (validChars.find_first_of(guess[i]) != std::string::npos) {
// whatever
}
或者:
if (std::strchr("AaBbCcDd", guess[i])) {
// whatever
}