C++数组故障
C++ Array Troubles
我试图构建一个井字游戏,由于某种原因,当我试图将一个值放入任何值时,似乎遇到了一个错误,它似乎将所选角色(比如玩家1,因此是一个"X")放入用户选择的值(他希望它在哪里),但也令人恼火地放入数组的[1][2]和[2][0]。随附代码。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace System;
using namespace std;
string game_board[2][2];
bool exit_condition = false;
int x_coords;
int y_coords;
int current_player;
string cp_char;
int returnxwin();
int returnowin();
int main()
{
cout << "Welcome to Tic-Tac-Toe Console!n" << endl;
//Start of game
while(exit_condition != true){
cout << "This is the game board: " << endl;
cout << " - | 1 | 2 | 3 | " << endl;
cout << " 1 | " << game_board[0][0] <<" | " <<game_board[1][0] << " | " << game_board[2][0] << " | " <<endl;
cout << " 2 | " << game_board[0][1] <<" | " <<game_board[1][1] << " | " << game_board[2][1] << " | "<<endl;
cout << " 3 | " << game_board[0][2] <<" | " <<game_board[1][2] << " | " << game_board[2][2] << " | n"<<endl;
//TESTING PURPOSES BE SURE TO REMOVE!
current_player = 1;
//Says which player is first
cout << "Player " << current_player << " is first!" << endl;
//Determines which player is first, and if so, which character to give to them.
if(current_player == 1)
{
cp_char = "X";
} else if(current_player == 2)
{
cp_char = "Y";
}
bool valid_input = false;
while(valid_input != true){
cout << "Where would you like to place your " << cp_char << " ? (X co-ordinates(top row))n" ;
cin >> x_coords;
cout << "Where would you like to place your " << cp_char << " ? (Y co-ordinates(side row))n" ;
cin >> y_coords;
if((x_coords <= 3) && (y_coords <=3))
{
if(game_board[x_coords-1][y_coords-1] == "")
{
game_board[1][2] = "";
game_board[2][0] = "";
//Problem Here!
game_board[x_coords-1][y_coords-1] = cp_char;
break;
valid_input = true;
}
else
{
cout << "Invalid Input! Somebody has already taken the slot!" << endl;
}
}
else
{
cout << "Invalid input! Please enter a number from 1 to 3" << endl;
}
}
//End of Valid Input Loop
//make sure to remove break;
// break;
}
system("pause");
return 0;
}
我还没有完成比赛,但不知道为什么会发生这种情况:s
另一方面,我也在寻找一种方法来随机决定玩家1还是2先上场。
编辑:我试着按照建议做了[3][3],但它仍然给了我一个错误。想法?
game_board
被定义为2x2字符串的数组,它应该是3x3吗?
string game_board[3][3]
我猜你是在遍历数组,所以得到了未定义的结果。。
关于有一种随机选择哪个玩家将开始的方法,只需使用rand()
功能:
srand(time(NULL)); // to initialize the random sequence
current_player = rand()%2 + 1; //player will be either 1 or 2
string game_board[2][2];
这为游戏板分配了2个宽乘2个高的条目。这比USTTTA/IOCTTT批准的锦标赛游戏板还小。试试这个:
std::string game_board[3][3];
相关文章:
- 数组的指针从不分段故障
- C 2D数组导致分割故障(核心倾倒)
- 试图创建动态分配的char数组时的分割故障
- 分割故障 - 遇到问题,创建新的数组实例
- 将内存分配给指针数组时SEG故障
- C AVX2:访问数组数组中的地址时SEG故障
- 处理2D数组时的分割故障
- 具有相同数组索引的C 分割故障
- 试图打印出/加载2D数组时的分割故障
- 输入坐标分为与文件故障的两个单独的数组
- 在一个动态分配的数组的程序中分割故障
- 简单的C++字符数组加密功能 - 段故障
- 分段故障当char数组在功能中声明时
- LinkedList分割故障的C 数组
- Seg故障是由于试图访问超出范围的数组,原因不明
- 循环中的数组出现故障
- CIN 一个非常大的 int 数组,段故障 11
- c++ 插入数组算法故障
- C++-分段故障-动态数组
- C++数组故障