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!
This question is related to
c++
compiler-errors
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
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'
"y" is a string/array/pointer. 'y' is a char/integral type
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
Source: Stackoverflow.com