#include "stdafx.h"
#include <list>
#include <iostream>
#include <string>
using namespace std;
class Canvas
{
public:
void CleanCanvas(Canvas * Canvas);
int canvas[10][10];
void setCoords(int X,int Y,bool run);
bool Win(Canvas * Canvas,string * WinningPlayer);
}CANVAS;
int _tmain(int argc, _TCHAR* argv[])
{
string coords;
string temp;
int X,Y;
bool flag = true;
bool run = false;
string WinningPlayer = "";
system("color 02");
printf("------------------------------//TIC-TAC-TOE//------------------------\n\n\n\n\n");
printf(" *********************************************** \n\n\n");
printf("Example: player1- 3,3 to put a mark on 3 line of the 3 column\n\n\n\n\n\n");
CANVAS.CleanCanvas((Canvas*)&CANVAS.canvas);
cin.get();
while(flag)
{
printf("player1 make the mov: ");
cin >> coords;
X = atoi((char *)coords.at(0));
Y = atoi((char *)coords.at(2));
if(CANVAS.canvas[X][Y] != 0)
{
printf("Coords alrady taken...set new");
cin >> coords;
X = coords.at(1);
Y = coords.at(3);
}
run = false;
CANVAS.setCoords(X,Y,run);
if(CANVAS.Win((Canvas*)&CANVAS.canvas,&WinningPlayer) == true)
{
printf("%s Win",WinningPlayer);
flag = false;
}
printf("player2 make the mov: ");
cin >> coords;
X = coords.at(1);
Y = coords.at(3);
if(CANVAS.canvas[X][Y] != 0)
{
printf("Coords alrady taken...set new");
X = coords.at(1);
Y = coords.at(3);
}
}
cin.get();
return 0;
}
void Canvas::setCoords(int X,int Y,bool run)
{
if(run == false)
{
CANVAS.canvas[X][Y] = 1;
}else
{
CANVAS.canvas[X][Y] = 2;
}
}
void Canvas::CleanCanvas(Canvas * Canvas)
{
for (int i = 0; i <= 3; i++)
{
for(int a = 0; a <= 3; a++)
{
Canvas->canvas[i][a] = 0;
}
}
}
bool Canvas::Win(Canvas * Canvas,string * WinningPlayer)
{
int count = 0;
for(int i = 0; i <= 3; i++)
{
for(int a = 0; a <= 3; a++)
{
switch(Canvas->canvas[i][a])
{
case 1: count +=1;
break;
case 2: count *=2 + 1;
break;
}
if(count == 9)
{
WinningPlayer = (string *)"player2";
return true;
}else if (count == 3)
{
WinningPlayer = (string *)"player1";
return true;
}
}
}
}
上面的代码给了我一个访问违规,我看到来自
X = atoi((char *)coords.at(0));
Y = atoi((char *)coords.at(2));
我试图在一些临时变量中使用coords.at,但它没有用 不要看代码,因为它只是一个镜头所以它不应该处理异常...... 我需要帮助才能弄清楚真正的问题是什么......谢谢!
答案 0 :(得分:2)
coords.at(0)
会返回char
,而非char*
。首先尝试解析std :: string,将每个数字转换为char*
,然后使用atoi
。