gpt4 book ai didi

使用 atoi() 函数的 C++ 访问冲突

转载 作者:行者123 更新时间:2023-11-28 02:57:51 25 4
gpt4 key购买 nike

#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 转换为临时变量,但没有成功不要看代码,因为它只是一个镜头,所以它不应该处理异常......我需要帮助找出真正的问题是什么...谢谢!

最佳答案

coords.at(0) 返回一个 char,而不是一个 char*。首先尝试解析您的 std::string,将每个数字转换为 char*,因此,您使用 atoi

关于使用 atoi() 函数的 C++ 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21581662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com