[英]ISO C++ forbids comparison between pointer and integer[-fpermissive] in C++ code
There is a problem with my code. 我的代码有问题。 It always return an error ISO C++ forbids comparison between pointer and integer[-fpermissive].
它总是返回错误ISO C ++禁止在指针和整型[-fpermissive]之间进行比较。 Can you help me see what is the problem here and how to solve it?
您能帮我看看这里有什么问题以及如何解决吗?
#include <iostream>
using namespace std;
char x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
#include <iostream>
char
is not a string, it is a character, means an integer (signed between -128 and 127 on most compiler implementations) char
不是字符串,而是字符,表示整数(在大多数编译器实现中在-128和127之间签名)
If you change the type of x
to string
it will do what you want 如果将
x
的类型更改为string
,它将执行您想要的操作
You had a raw C comparison char
vs char *
which explains the error message 您有一个原始的C比较
char
vs char *
,它解释了错误消息
By turning the char
into a string
you activate the string::operator==
which accepts char *
as a convenience and performs a string comparison, which is intuitively what you want to do. 通过将
char
转换为string
可以激活string::operator==
,它方便地接受char *
并执行字符串比较,这在直觉上就是您想要执行的操作。
My advice is: keep going with C++ and never use char *
, malloc
or all that C stuff likely to fail, stick to std::string
, and use std::string::c_str()
to get the string contents as const char *
for use with C primitives if needed. 我的建议是:继续使用C ++,并且永远不要使用
char *
, malloc
或所有可能会失败的C东西,坚持使用std::string
,并使用std::string::c_str()
来获取字符串内容作为const char *
必要时用于C原语。 A positive side-effect is that it will avoid the trap of comparing 2 char *
types with ==
operator, which compare pointers and not values. 一个积极的副作用是它将避免使用
==
运算符比较2个char *
类型的陷阱,该运算符比较指针而不是值。
using namespace std;
string x;
int main()
{
cout << "Welcome to the citation machine. What do you want to cite?" << endl;
cin >> x;
if (x == "book")
{
cout << "What is the name of the book?";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.