1

我正在开发一个网络编程项目来编写客户端服务器 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 的随机整数(石头纸或剪刀)

找到赢家():

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);
}
}
4

1 回答 1

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"};

你确定 player 永远不会是负数或大于 3 吗?

printf("Client: %s\n",items[player-1]);
printf ("Computer: %s\n",items[pc-1]);
于 2012-11-30T06:57:24.010 回答