我想写一个包含2名玩家的TicTacToe程序(我正在从Jumping into C++
进行练习)。下面的语法没有任何错误,但是假设我输入1或2,程序只是退出而没有任何错误或任何结果。这是我想出的代码:
#include <iostream>
using namespace std;
int board_pos;
int main()
{
cout << "Enter => 1 for X; 2 for O:" << endl;
enum TTT_Board{topLeft, topMid, topRight, middleLeft, middleMid, middleRight, botLeft, botMid, botRight};
cout << "-------" << endl;
cout << "|" << topLeft << "|" << topMid << "|" << topRight << "|" << endl; /* Top cells of the board */
cout << "-------" << endl;
cout << "|" << middleLeft << "|" << middleMid << "|" << middleRight << "|" << endl;
cout << "-------" << endl;
cout << "|" << botLeft << "|" << botMid << "|" << botRight << "|" << endl;
cout << "-------" << endl;
if (board_pos == 0){
switch (board_pos) {
case topLeft:
cout << " " << endl;
break;
case topMid:
cout << " " << endl;
break;
case topRight:
cout << " " << endl;
break;
case middleLeft:
cout << " " << endl;
break;
case middleMid:
cout << " " << endl;
break;
case middleRight:
cout << " " << endl;
break;
case botLeft:
cout << " " << endl;
break;
case botMid:
cout << " " << endl;
break;
case botRight:
cout << " " << endl;
break;
default:
break;
}
}
else if (board_pos == 1)
{
switch (board_pos) {
case topLeft:
cout << "X" << endl;
break;
case topMid:
cout << "X" << endl;
break;
case topRight:
cout << "X" << endl;
break;
case middleLeft:
cout << "X" << endl;
break;
case middleMid:
cout << "X" << endl;
break;
case middleRight:
cout << "X" << endl;
break;
case botLeft:
cout << "X" << endl;
break;
case botMid:
cout << "X" << endl;
break;
case botRight:
cout << "X" << endl;
break;
default:
break;
}
}
else if (board_pos == 2)
{
switch (board_pos) {
case topLeft:
cout << "O" << endl;
break;
case topMid:
cout << "O" << endl;
break;
case topRight:
cout << "O" << endl;
break;
case middleLeft:
cout << "O" << endl;
break;
case middleMid:
cout << "O" << endl;
break;
case middleRight:
cout << "O" << endl;
break;
case botLeft:
cout << "O" << endl;
break;
case botMid:
cout << "O" << endl;
break;
case botRight:
cout << "O" << endl;
break;
default:
break;
}
}
else {
cout << "Please enter: 1 for X, 2 for O, and 0 if you want you skip the cell";
}
cin >> board_pos;
}
注意:程序确实编译了!
答案 0 :(得分:5)
您应该将所有逻辑代码提取到单独的函数中,然后在cin
中的while
循环中执行main()
,当用户输入非数字时退出。< / p>
你不应该递归地调用main
。
答案 1 :(得分:5)
您递归调用main()
。
标准规定:
3.6.1.3
&#34;函数main不得在程序中使用。&#34;
5.2.2.9
&#34;允许递归调用,但名为main&#34;
的函数除外
在您对main()
的递归调用后,您正在阅读用户输入,如果此调用成功,将无法让您的用户输入任何内容。
编译的程序不一定是好的程序。