gpt4 book ai didi

c++ - 将字符串与 C++ 中的一组字符进行比较

转载 作者:行者123 更新时间:2023-11-30 00:52:25 25 4
gpt4 key购买 nike

我正在尝试获取一串并列字符,以便根据一组“有效”字符进行解析。如果字符串都是“有效”集合中的字符,则代码应继续。但是,如果字符串包含除有效集之外的任何字符,它应该返回错误并提示重新输入,再次检查有效性。

我想出了两组不同的代码来执行检查,其中“guess”是输入字符串,A、a、B、b、C、c、D 和 d 是允许的字符。第一组代码似乎第一次运行正确,然后接受任何东西,第二组代码在进入循环后将只接受单个有效字母输入。不过看了之后,问题似乎以某种方式 Root 于逻辑语句。无论如何,我们将不胜感激。

代码#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

最佳答案

逻辑语句坏了,应该这样读

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;
}

关于c++ - 将字符串与 C++ 中的一组字符进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19239993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com