无法比较指针和整数c ++

时间:2015-11-21 17:53:37

标签: c++ pointers char

您好我正在尝试编写一个简单的tic tac toe游戏,每当我编译它时说:

error: ISO C== forbids comparison between pointer and integer
[-fpermissive]  } while(input != "Quit");
                                 ^

这是我的代码:

#include <iostream>
using namespace std;

/*
Board;
 1 | 2 | 3
---|---|---
 4 | 5 | 6
---|---|---
 7 | 8 | 9
*/

char square[9] = {'1','2','3','4','5','6','7','8','9'};

char input;

void board();

main()
{
    do
    {
        board();
        switch (input)          
        {
            case 1:
                square[1] = 'X';
            case 2:
                square[2] = 'X';
            case 3:
                square[3] = 'X';
            case 4:
                square[4] = 'X';
            case 5:
                square[5] = 'X';
            case 6:
                square[6] = 'X';
            case 7:
                square[7] = 'X';
            case 8:
                square[8] = 'X';
            case 9:
                square[9] = 'X';
            default:
                cout << "Invalid Input";
        }
    } while(input != "Quit");     //Here is where it is an error

    if(input == "Quit")
    {
        return 1;
    }

    cout << "\n\n"; 

    return 0;
}

void board()                //Builds the board
{
    cout << "\n\n\tTicTacToe\n\n";

    cout<<" "<<square[0]<<" | "<<square[1]<<" | "<<square[2]<< endl;
    cout << "---|---|---" << endl;

    cout<<" "<<square[3]<<" | "<<square[4]<<" | "<<square[5]<< endl;
    cout << "---|---|---" << endl;

    cout<<" "<<square[6]<<" | "<<square[7]<<" | "<<square[8]<< endl;

    cout << "Player 1 Make a Move:  ";
    cin.get();
    cin >> input;
}

仅供参考,这并不接近完整游戏,我只想弄清楚我将如何编写游戏的某些部分。

4 个答案:

答案 0 :(得分:0)

问题在于变量input被声明为单个char数据类型,并且您将其与字符串进行比较,或者在本例中为const char*,基本上是字符数组。由于"Quit"是一个字符数组,因此您无法将其等同为单个char

答案 1 :(得分:0)

当你尝试分配或比较两个变量时,左运算符类型必须与右运算符类型相同,在输入casse le left运算符时,char类型的变量和左变量类型“Quit”是类型const char [4],有两种类型不同,无法比较!

答案 2 :(得分:0)

在if中,您要将charchar *进行比较。

将if中的值设置为

'Q'

或使用

声明输入变量
char *input;

考虑查看字符串标题,它包含在这种情况下非常有用的功能。

修改:您的代码出现了另一个错误:在您的切换案例中,每个break;后都不会包含case :。这将导致正确案例后的所有内容变为'X'

编辑2:你不应该使用全局变量。只需通过引用传递它们。

编辑3:main()应该有一个类型。

答案 3 :(得分:0)

在您的switch声明中,您正在访问不存在的square[9]。这称为缓冲区溢出,您可能会覆盖其他变量或代码。

使用board()功能进行检查,该功能可正确访问阵列。