[英]Problem with comparison between pointer and integer C++
我收到错误消息说
[错误] ISO C ++禁止比较指针和整数[-fpermissive]
而且不知道如何解决。
我已经在stackoverflow上搜索了同样问题的人,但只想到了这一点: c ++编译错误:ISO C ++禁止比较指针和整数 ,这没有回答我的问题。 也让我感到困惑的是,错误出现在这里的HERE注释所指示的线上,这是if语句,但是我在条件部分看不到任何整数。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int main() {
char in[100];
gets(in);
int len = strlen(in);
std::string s(in);
int count = 0;
for (int i = 0; i < len; i++) {
if (s.at(i) == " ") { // <-- HERE
count += 1;
}
}
cout << count;
}
假设输入为Hello World,我期望输出为1
,但没有任何输出。
表达式" "
是类型为const char [2]
的字符串文字 。
表达式s.at(i)
返回char&
。
因此, s.at(i) == " "
试图找到在左边使用char&
并在右边引用文字数组const char(&)[4]
的相等运算符。
它为operator==
找到一个或多个候选,但是参数类型不完全匹配,因此接下来尝试隐式转换序列 -这是char&
进行整数提升为int
,而数组衰减为const char*
。
它仍然找不到与之匹配的对象,并放弃了,但这解释了为什么在发出错误时它具有int
和const char *
参数。
这么说很长,您在C ++中编写了像' '
这样' '
字符文字。 它们不仅像其他一些语言一样是长度为1的字符串(而且您根本无法编写带有单引号的字符串)。
更改if语句
if (s.at(i) == ' ') {
count += 1;
}
因为s.at(i)
返回char&,所以" "
是字符串,而' '
是字符。
问题是" "
是字符串文字而不是字符! 字符文字为' '
。
该错误有点令人误解,因为" "
实际上是const char*
。
C ++通过不同的引号( "
vs '
)区分字符串中的字符串和单个字符 。代码中的" "
是包含一个空格的字符串文字,单个空格字符将被写为' '
std::string::at
函数std::string::at
返回单个字符。
一个小例子将向您展示编译器对此的外观
#include <iostream>
#include <string>
#include <typeinfo> // for typeid
using namespace std;
int main() {
string s = "Hello, world!";
cout << typeid(" ").name() << endl;
cout << typeid(' ').name() << endl;
cout << typeid(s.at(0)).name() << endl;
return 0;
}
参见上面代码的在线演示 。
但是,确切地说,C ++中的比较不需要相同的类型,但是类型必须兼容 。 指针(字符串文字被认为是指向字符的常量指针,实际上指向文字中的第一个字符)与整数(在您的情况下, char
被提升为char
)是不兼容的 。 为了快速“解决”您的问题, s.at(i) == " "
更改为s.at(i) == ' '
,但是您的程序仍然会出现问题:它仍然包含很多有问题的C代码自我也是。 可能的C ++版本可能是这样的:
#include <iostream>
#include <string>
using namespace std;
int main() {
int count = 0;
string line;
std::getline(cin, line);
for (const auto c: line) {
if (c == ' ') {
count++;
}
}
cout << "Your input \""<< line << "\" contains " << count << " space(s)." << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.