如何使用 if else 语句
How to use if else statement
今天我想测试用户是否在控制台应用程序中键入单词"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";
}
}
我一直得到"是"没有在范围内定义。 任何帮助将不胜感激。谢谢!
代码中至少存在以下问题:
-
令牌
yes
和no
是标识符。如果你想让他们成为角色,那将是'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";
}
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 我似乎对if/else的基本语句有问题:/
- 如果 else 语句不断循环
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 如果 else 语句使用大写和小写字母
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 多个'if'语句,不带'else'
- 嵌套的 else 语句 c++
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- if-else 语句仅按特定顺序工作,我不知道为什么
- "if else"被视为单个语句吗?
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误