谁能帮我处理C++中的语句和字符串
Could anyone help me with if statements and strings in C++?
我在 c++ 中的 if 语句和字符串/字符方面遇到了一些麻烦。这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "-----------------------------" << endl;
cout << "|Welcome to Castle Clashers!|" << endl;
cout << "-----------------------------" << endl;
cout << "Would you like to start?" << endl;
string input;
cout << "A. Yes ";
cout << "B. No " << endl;
cin >> input;
if(input == "a" || "A"){
cout << "Yes" << endl;
}else{
if(input == 'b' || 'B'){
return 0;
}
}
return 0;
}
在我的 if 语句中,它检查字符串输入是否等于 yes,如果不是,则应转到 else 语句。这就是麻烦开始的地方,一旦我在控制台中运行我的程序,当我键入除"a"或"A"以外的任何内容时,它仍然说是。我尝试使用字符/字符执行此操作,但我得到相同的输出。谁能帮我?
它应该是input == "a" || input == "A"
.您必须单独测试每个案例。现在你的代码等效于 (input == "a") || "A"
,它的计算结果是true
,因为"A"
衰减到非零指针。
"A"
和'B'
在典型实现中将始终为真。
您还应该将input
与他们进行比较。
此外,似乎不支持将std::string
与char
进行比较,因此您还应该对b
和B
使用字符串文本。
Try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "-----------------------------" << endl;
cout << "|Welcome to Castle Clashers!|" << endl;
cout << "-----------------------------" << endl;
cout << "Would you like to start?" << endl;
string input;
cout << "A. Yes ";
cout << "B. No " << endl;
cin >> input;
if(input == "a" || input == "A"){
cout << "Yes" << endl;
}else{
if(input == "b" || input == "B"){
return 0;
}
}
return 0;
}
C 没有"真正的"布尔值 - 相反,任何等于 0 的东西都被认为是假的,任何与此不同的值都被认为是真的。虽然C++引入了bool
类型,但出于兼容性原因,它仍然保持旧的 C 行为。
正如 Cornstalk 所说,你的(input == "a" || "A")
与 ((input == "a") || ("A"))
相同,并且"A" != 0
,所以它总是计算为 true
- 这就是为什么它总是会进入 if 块。 你想要的是:
if (input == "a" || input == "A")
下一条语句也是如此(将其与"B"进行比较),但还有一个额外的问题:您使用单引号 ( ' ) 而不是双引号 ( "),这使它成为char
而不是string
。要使两个变量的类型相同,只需使用双引号,结果如下:
if(input == "b" || input == "B")
- Switch 语句(字符串)一直选择默认值,除非其为零
- 有没有办法在C++将字符串与开关语句一起使用?
- 我如何将 OR 与 if 语句一起使用字符串
- PostgresSQL - SQL Ready 语句与字符串转义,防止 SQL 注入攻击
- C++ 虽然语句不适用于字符串和"or"
- 这两个C++语句连接字符串有什么区别?
- 不能在 if 语句 - c++ 中使用 void func 直接将字符串转换为大写
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 是否可以对任何语句字符串使用预准备语句?
- 为什么我的 if 语句不适用于 c++ 中的字符串?
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- 如何比较if语句中的字符串?
- C++字符串和 while 语句的问题
- 与 IF 语句C++的字符串比较?
- 使用 if 语句C++字符串变量
- QSqlQuery:在执行之前获取准备好的语句字符串