Morlock
Morlock

Reputation: 7131

c++ compile error: ISO C++ forbids comparison between pointer and integer

I am trying an example from Bjarne Stroustrup's C++ book, third edition. While implementing a rather simple function, I get the following compile time error:

error: ISO C++ forbids comparison between pointer and integer

What could be causing this? Here is the code. The error is in the if line:

#include <iostream>
#include <string>
using namespace std;
bool accept()
{
    cout << "Do you want to proceed (y or n)?\n";
    char answer;
    cin >> answer;
    if (answer == "y") return true;
    return false;
}

Thanks!

Upvotes: 42

Views: 183681

Answers (5)

Craig
Craig

Reputation: 1219

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

Upvotes: 8

Danny Mahoney
Danny Mahoney

Reputation: 1255

You must remember to use single quotes for char constants. So use

if (answer == 'y') return true;

Rather than

if (answer == "y") return true;

I tested this and it works

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223003

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

Upvotes: 56

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

A string literal is delimited by quotation marks and is of type char* not char.

Example: "hello"

So when you compare a char to a char* you will get that same compiling error.

char c = 'c';
char *p = "hello";

if(c==p)//compiling error
{
} 

To fix use a char literal which is delimited by single quotes.

Example: 'c'

Upvotes: 7

Anycorn
Anycorn

Reputation: 51465

"y" is a string/array/pointer. 'y' is a char/integral type

Upvotes: 4

Related Questions