如何使用 if else 语句

How to use if else statement

本文关键字:语句 else if 何使用      更新时间:2023-10-16

今天我想测试用户是否在控制台应用程序中键入单词"yes",然后该功能将继续,但是,我无法这样做。(我是新人,对不起(

对此有任何帮助吗? 我知道在测试变量时,例如..int x = 14,如果(<14(打印一些东西。但我想尝试使用文本而不是数字。

以下是源代码:

int main()
{
char a = yes;
char b = no;
cout << "hi, press yes to start or no to cancel";
cin >> a;
if (a == yes)
{ 
cout << "Cool person";
}
else if(b == no)
{
cout << "not a cool person";
}
}

我一直得到"是"没有在范围内定义。 任何帮助将不胜感激。谢谢!

代码中至少存在以下问题:

  • 令牌yesno是标识符。如果你想让他们成为角色,那将是'yes''no。除了他们不是角色,因为他们太长了。所以,它们可能应该是像"yes""no"这样的字符串。

  • b变量在这里完全没用,你应该有一个变量来接收来自用户的信息,并根据多个可能的值进行检查。选择有意义的变量名称也是一个好主意。

  • 您没有包含必要的标头,也没有为std函数和类型使用正确的命名空间(通过为每个函数和类型显式预置std::,或者对所有函数和类型使用using namespace std(。

考虑到这一点,请尝试以下计划作为您继续教育的起点:

#include <iostream>
#include <string>
int main() {
std::string userInput;
std::cout << "Hi, enter yes to start or no to cancel: ";
std::cin >> userInput; // probably better: std::getline(std::cin, userInput);
if (userInput == "yes") {
std::cout << "Cool personn";
} else if (userInput == "no") {
std::cout << "Not a cool personn";
} else {
std::cout << "Hey, can't you read? I said yes or no :-)n";
}
}