当前位置: 动力学知识库 > 问答 > 编程问答 >

Cannot compare pointer and integer c++

问题描述:

Hi I am trying to program a simple tic tac toe game, and whenever I compile it says:

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

[-fpermissive] } while(input != "Quit");

^

Here is my code:

#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;

}

FYI, this isn't close to the full game, I am just trying to figure out how I will code some parts of the game.

网友答案:

The problem is that variable input is declared as a single char data type and you're comparing it with a string, or in this case a const char*, essentially an array of characters. Since "Quit" is an array of characters, you cannot equate that to a SINGLE char.

网友答案:

In the if, you are comparing a char to char *.

Either set the value in the if to

'Q'

Or declare the input variable using

char *input;

Consider looking at the string header, it includes features that are highly useful in this situation.

Edit: Another error with your code: In your switch case, you do not include a break; after each case :. This will cause every everything after the correct case to become 'X'.

Edit 2: You should NOT use global variables. Just pass them by reference.

Edit 3: main() should have a type.

网友答案:

In your switch statement, you are accessing square[9] which doesn't exist. This is called a buffer overrun and you may be overwriting other variable or code.

Review with your board() function, which accesses the array correctly.

网友答案:

When you try to assign or compare two variables the left operator type must be the same that le right operator type, in your casse le left operator is input, a variable of type char and the left variable type "Quit" is of type const char[4], there two types are different and can't be compare !

分享给朋友:
您可能感兴趣的文章:
随机阅读: