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

YWH*_*YWH 0 c++ pointers

我的代码有问题.它始终返回错误ISO C++禁止指针和整数[-fpermissive]之间的比较.你能帮我看看这里有什么问题以及如何解决?

#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?";
    }
}
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 12

#include <iostream>
Run Code Online (Sandbox Code Playgroud)

char 不是字符串,它是一个字符,表示一个整数(在大多数编译器实现上在-128和127之间签名)

如果更改的类型xstring它会做你想要什么

你有一个原始的C比较charvs char *解释错误信息

通过将你char变成一个string激活你string::operator==接受char *的方便并执行一个字符串比较,这是你想要做的直观.

我的建议是:继续使用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?";
    }
}
Run Code Online (Sandbox Code Playgroud)