ISO C++禁止在C++代码中比较指针和整数[-fpermissive]

ISO C++ forbids comparison between pointer and integer[-fpermissive] in C++ code

本文关键字:C++ 整数 -fpermissive 指针 比较 禁止 代码 ISO      更新时间:2023-10-16

我的代码有问题。它总是返回一个错误 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 比较charchar *,这解释了错误消息

通过将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?";
    }
}