YWH
YWH

Reputation: 35

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

There is a problem with my code. It always return an error ISO C++ forbids comparison between pointer and integer[-fpermissive]. Can you help me see what is the problem here and how to solve it?

#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?";
    }
}

Upvotes: 0

Views: 1586

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

#include <iostream>

char is not a string, it is a character, means an integer (signed between -128 and 127 on most compiler implementations)

If you change the type of x to string it will do what you want

You had a raw C comparison char vs char * which explains the error message

By turning the char into a string you activate the string::operator== which accepts char * as a convenience and performs a string comparison, which is intuitively what you want to do.

My advice is: keep going with C++ and never use char *, malloc or all that C stuff likely to fail, stick to std::string, and use std::string::c_str() to get the string contents as const char * for use with C primitives if needed. A positive side-effect is that it will avoid the trap of comparing 2 char * types with == operator, which compare pointers and not values.

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

Upvotes: 12

Related Questions