42

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!

Morlock
  • 6,880
  • 16
  • 43
  • 50
  • 18
    y in your code is a string literal (double quotes) `""`, a char is only (single quotes) `''` – Alex Feb 15 '10 at 02:11
  • 1
    Check your typing. The example in Stroustup has `char answer = 0;` and `if (answer == 'y') return true;`. – CB Bailey Feb 15 '10 at 07:56

5 Answers5

55

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

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
8

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

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
Craig
  • 1,199
  • 1
  • 13
  • 27
7

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
  • 339,232
  • 124
  • 596
  • 636
4

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

Anycorn
  • 50,217
  • 42
  • 167
  • 261
3

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

Danny Mahoney
  • 1,255
  • 2
  • 13
  • 24