【问题标题】:c++ compile error: ISO C++ forbids comparison between pointer and integerc++编译错误:ISO C++禁止指针和整数的比较
【发布时间】:2011-01-16 20:19:41
【问题描述】:

我正在尝试 Bjarne Stroustrup 的 C++ 书籍第三版中的一个示例。在实现一个相当简单的功能时,我得到以下编译时错误:

error: ISO C++ forbids comparison between pointer and integer

这可能是什么原因造成的?这是代码。错误在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;
}

谢谢!

【问题讨论】:

  • 您的代码中的 y 是字符串文字(双引号)"",字符仅是(单引号)''
  • 检查您的输入。 Stroustup 中的示例有char answer = 0;if (answer == 'y') return true;

标签: c++ compiler-errors


【解决方案1】:

您有两种方法可以解决此问题。首选方法是使用:

string answer;

(而不是char)。另一种可能的修复方法是:

if (answer == 'y') ...

(注意单引号而不是双引号,表示char 常量)。

【讨论】:

    【解决方案2】:

    字符串文字由引号分隔,类型为 char* 而不是 char。

    示例:"hello"

    因此,当您将 char 与 char* 进行比较时,您将得到相同的编译错误。

    char c = 'c';
    char *p = "hello";
    
    if(c==p)//compiling error
    {
    } 
    

    要修复使用由单引号分隔的字符文字。

    例如:'c'

    【讨论】:

      【解决方案3】:

      您需要将那些双引号更改为单引号。 IE。 if (answer == 'y') 返回true;

      以下是有关 C++ 中字符串文字的一些信息: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

      【讨论】:

      • 你的意思是双引号在c++中不能互换?
      • 不,双引号是char[](一堆字符),单引号是单个char
      • 刚刚为您发布了一个指向 msdn 库的链接。
      【解决方案4】:

      "y" 是一个字符串/数组/指针。 'y' 是一个字符/整数类型

      【讨论】:

        【解决方案5】:

        您必须记住对 char 常量使用单引号。 所以使用

        if (answer == 'y') return true;

        而不是

        if (answer == "y") return true;

        我对此进行了测试,它可以工作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多