C++ 为什么在接受输入后退出循环时不这样做
非常直截了当。我不明白为什么它在不接受y字符后不退出循环 我尝试了==和!=的不同变体关于y字符和n字符C++ 为什么在接受输入后退出循环时不这样做,c++,visual-c++,vector,while-loop,C++,Visual C++,Vector,While Loop,非常直截了当。我不明白为什么它在不接受y字符后不退出循环 我尝试了==和!=的不同变体关于y字符和n字符 vector<int> v; char ans; do { cout << "Enter scores, enter number outside of 0-100 to stop:\n"; get_scores(v); print_stats(v); cout <<
vector<int> v;
char ans;
do
{
cout << "Enter scores, enter number outside of 0-100 to stop:\n";
get_scores(v);
print_stats(v);
cout << "Do you want to try another set of scores? Y/N: \n";
cin >> ans;
} while (ans != ('n' || 'N'));
向量v;
查尔安斯;
做
{
库坦斯;
}而(ans!=('n'n');
键入任何字符后,循环都会不断请求更多输入。
注意:get scores(获取分数)和print stats(打印统计数据)函数按其预期的方式工作。您在while条件下的比较不正确,您可能是有意这样做的
while(ans!=“n”&&ans!=“n”);
('n'|'n')
将强制为true(1),因此您将检查值为1的字符,而不是'n'
/'n'
} while (ans != ('n' || 'N'));
在这里,您将比较char与其他两个char的| |运算的布尔结果。
这通常被认为是正确的。
所以你的while语句是有效的
} while (ans != true);
要解决此问题,您需要将ans与n和n进行比较,并在其中一个为真时退出,例如:
} while ((ans != 'n') && (ans != 'N'));
while(ans!=('n'| |'n'))
与编写while(ans!=(true))
相同。您可能想要,而((ans!=“n”)&&(ans!=“n”)
@JesperJuhl答案属于答案部分