我正在编写一个网络编程项目来编写客户端服务器Rock Paper Scissors代码。我完成了代码,它在测试期间运行良好,然后我将这行添加到代码中。
findWinner(gameType,pcChoice);
当我在代码中添加代码时,代码开始向我提供有关服务器端的分段错误的错误。这是我添加该行的地方。
while(1)
{
int gameType;
printf("Paper, Scissors, Rock game start.\n");
rc = read(client_sockfd, &gameType, 1);
srand(time(NULL));
pcChoice = (rand() % 3)+1;
findWinner(gameType,pcChoice);
gameType = pcChoice;
write(client_sockfd, &gameType, 1);
}
我是C的成熟者,不知道该怎么做。
int pcChoice;
它是一个整数,用于保持1到3的随机整数(石头纸或剪刀)
findwinner():
void findWinner(int player,int pc)
{
const char *items[3]={"Paper","Scissors","Rock"};
printf("Client: %s\n",items[player-1]);
printf ("Computer: %s\n",items[pc-1]);
switch (player)
{
case 1:
switch (pc)
{
case 1:
printf("it is a DRAW\n");
break;
case 2:
printf("Computer Wins\n");
break;
case 3:
printf("Computer Loses\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
case 2:
switch (pc)
{
case 1:
printf("Computer Loses\n");
break;
case 2:
printf("it is a DRAW\n");
break;
case 3:
printf("Computer Wins\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
case 3:
switch (pc)
{
case 1:
printf("Computer Wins\n");
break;
case 2:
printf("Computer Loses\n");
break;
case 3:
printf("it is a draw\n");
break;
default:
printf("ERROR\n");
exit(0);
};
break;
default:
printf("ERROR\n");
exit(0);
}
}
答案 0 :(得分:2)
while(1)
{
int gameType;
printf("Paper, Scissors, Rock game start.\n");
rc = read(client_sockfd, &gameType, sizeof(gameType));
srand(time(NULL));
pcChoice = (rand() % 3)+1;
findWinner(gameType,pcChoice);
gameType = pcChoice;
write(client_sockfd, &gameType, sizeof(gameType));
}
其他可能有问题的事情是:
尝试显式null终止char*
const char *items[3]={"Paper\0","Scissors\0","Rock\0"};
你确定玩家永远不会消极或大于3吗?
printf("Client: %s\n",items[player-1]);
printf ("Computer: %s\n",items[pc-1]);