ISO C++禁止在C++代码中比较指针和整数[-fpermissive]
ISO C++ forbids comparison between pointer and integer[-fpermissive] in C++ code
我的代码有问题。它总是返回一个错误 ISO C++禁止在指针和整数[-fallowive]之间进行比较。你能帮我看看这里有什么问题以及如何解决它吗?
#include <iostream>
using namespace std;
char x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
#include <iostream>
char
不是字符串,它是一个字符,表示一个整数(在大多数编译器实现中,符号在 -128 和 127 之间(
如果您将x
类型更改为string
它将执行您想要的操作
您有一个原始的 C 比较char
与char *
,这解释了错误消息
通过将char
转换为string
,您可以激活接受char *
作为方便并执行字符串比较的string::operator==
,这直观地是您想要做的。
我的建议是:继续使用C++,永远不要使用char *
,malloc
或所有可能失败的C内容,坚持使用std::string
,并使用std::string::c_str()
来获取字符串const char *
内容,如果需要,可以与C原语一起使用。一个积极的副作用是,它将避免将 2 种char *
类型与==
运算符进行比较的陷阱,运算符比较指针而不是值。
using namespace std;
string x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组