C++ if 语句故障
如果我输入 Artist,我也会从 Artist 得到 if 以及 else 语句。我看不出问题是什么,它编译得很好,但仅在大写字母 Artist 上,它给了我对 Artist 的双重价值,一切都很好。
cin >> answer;
if (answer == "Artist") {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
cout << "Playing music like a boss" << endl;
Drums = (Drums + 1);
Base = (Base + 1);
}
if (answer == "artist") {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
cout << "Playing music like a boss" << endl;
Drums = (Drums + 1);
Base = (Base + 1);
}
else {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "You should buy a guitar" << endl;
Drums = (Drums + 1);
Bag = (Bag - 1);
}
[编辑] 好的,我将代码更改为使用 if 语句,但问题仍然存在。
If I enter Artist I will get the if from the Artist plus the else statement too. I cant see what the problem is it compiles fine but only on capital letter Artist it gives me double value on artist all is good.
cin >> answer;
if (answer == "Artist") {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
cout << "Playing music like a boss" << endl;
Drums = (Drums + 1);
Base = (Base + 1);
}
if (answer == "artist") {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 6);
cout << "Playing music like a boss" << endl;
Drums = (Drums + 1);
Base = (Base + 1);
}
else {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "You should buy a guitar" << endl;
Drums = (Drums + 1);
Bag = (Bag - 1);
}
[EDIT] Okay, I changed the code to using if statements but the problem remains.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
现在的情况是,如果字符串包含“Artist”,那么您将执行该块,“artist”检查失败并执行 else 块。
您很可能想要:
这将使得只有一个块将被执行。
The way it is now, if the string contains "Artist" then you will execute that block, fail the check for "artist" and execute the else block.
You most likely want:
This will make it so only one of the block will be executed.
您不能在
switch
语句中使用字符串。switch
中只能使用整型常量。您必须使用一系列if
语句。You can't use strings in
switch
statements. Only integral constants can be used inswitch
. You'll have to use a series ofif
statements.这是如何运作的?您无法打开字符串,必须使用字符串相等性来检查。
switch 语句 编译为跳转表,其中输入本质上是选择跳转中的目标表被采取。所以你的开关输入必须是一体型的。不是字符串。
How does this work? You cannot switch on a string, you have to use string equality to check.
A switch statement compiles down to a jump table, where the input is essentially choosing which target in the jump table is taken. So your switch input has to be of an integral type. Not a string.
C++ 不是我最擅长的语言,但我理解使用带有 String 的 switch 具有未定义的行为。
C++ is not my strongest language, but my understanding that using switch with a String has undefined behavior.