c++ 编译错误:ISO C++ 禁止指针和整数之间的比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2263681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ compile error: ISO C++ forbids comparison between pointer and integer
提问by Morlock
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:
我正在尝试 Bjarne Stroustrup 的 C++ 书,第三版中的一个例子。在实现一个相当简单的函数时,我得到以下编译时错误:
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:
什么可能导致这种情况?这是代码。错误在if
一行中:
#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!
谢谢!
回答by Chris Jester-Young
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:
(而不是char
)。另一种可能的修复方法是:
if (answer == 'y') ...
(note single quotes instead of double, representing a char
constant).
(注意单引号而不是双引号,代表一个char
常量)。
回答by Brian R. Bondy
A string literal is delimited by quotation marks and is of type char* not char.
字符串文字由引号分隔,类型为 char* 而不是 char。
Example: "hello"
例子: "hello"
So when you compare a char to a char* you will get that same compiling error.
因此,当您将 char 与 char* 进行比较时,您将得到相同的编译错误。
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'
例子: 'c'
回答by Craig
You need the change those double quotation marks into singles.
ie. if (answer == 'y')
returns true
;
您需要将那些双引号更改为单引号。IE。if (answer == 'y')
返回true
;
Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx
以下是有关 C++ 中字符串文字的一些信息:http: //msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx
回答by Anycorn
"y" is a string/array/pointer. 'y' is a char/integral type
“y”是一个字符串/数组/指针。'y' 是字符/整数类型
回答by Danny Mahoney
You must remember to use single quotes for char constants. So use
您必须记住对 char 常量使用单引号。所以用
if (answer == 'y') return true;
if (answer == 'y') return true;
Rather than
而不是
if (answer == "y") return true;
if (answer == "y") return true;
I tested this and it works
我测试了这个并且它有效