views:

413

answers:

4

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!

+4  A: 

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

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

Craig
You mean that double quotation marks are not interchangable in c++?
Morlock
No, double quotes are `char[]` (a bunch of characters), single quotes is a single `char`.
Chris Jester-Young
just posted a link for you to msdn library.
Craig
+2  A: 

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

aaa
+1  A: 

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'

Brian R. Bondy
+6  A: 

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).

Chris Jester-Young