由于 Visual Studio Ultimate 2013 中的 scanf_s,程序正在崩溃

Program is crashing because of scanf_s in Visual Studio Ultimate 2013

我刚刚开始使用 C 语言,因为我的大学有一些编程课程。当我们在 Dev C++ 程序中编程时,我从高中就知道一点 C。现在我们需要为它使用 Visual Studio,我编写的下一个程序在 Dev C++ 中运行良好,但在输入名称后崩溃。在开发 C++ 中,我从 strcatscanf 中删除了 _s 并且它工作得很好。有人可以帮我解决这个问题吗?这个程序是关于输入一个名字的,它应该随机将你置于这两个团队之一。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

int main() {
    int maxPlayers = 16, player, teamForming, numPlayer1 = 0, numPlayer2 = 0;
    char blueTeam[256] = "", redTeam[256] = "", name[16];
    for (player = 1; player <= maxPlayers; player++) {
        printf("\nEnter a name of %d. player : ", player);
        scanf_s(" %s", name);
        teamForming = rand() % 2;
        if (teamForming == 0) {
            if (numPlayer1 == 8) {
                strcat_s(redTeam, name);
                strcat_s(redTeam, " ");
                numPlayer2++;
                break;
            }
            strcat_s(blueTeam, name);
            strcat_s(blueTeam, " ");
            numPlayer1++;
        } else {
            if (numPlayer2 == 8) {
                strcat_s(blueTeam, name);
                strcat_s(blueTeam, " ");
                numPlayer1++;
                break;
            }
            strcat_s(redTeam, name);
            strcat_s(redTeam, " ");
            numPlayer2++;
        }
    }
    printf("\nBlue team : %s.\n", blueTeam);
    printf("\nRed team : %s.\n", redTeam);
    return 0;
}

scanf_sscanf 语义略有不同:对于 s[ 格式,您必须传递目标数组的大小:

scanf_s(" %s", name, sizeof(name));

类似地,strcat_s 将目标数组和源字符串之间的第三个参数作为目标数组中元素的计数。

这是您的代码的修改版本:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    int maxPlayers = 16, player, teamForming, numPlayer1 = 0, numPlayer2 = 0;
    char blueTeam[256] = "", redTeam[256] = "", name[16];
    for (player = 1; player <= maxPlayers; player++) {
        printf("\nEnter a name of %d. player : ", player);
        scanf_s(" %s", name, sizeof(name));
        teamForming = rand() % 2;
        if (teamForming == 0) {
            if (numPlayer1 == 8) {
                strcat_s(redTeam, sizeof(redTeam), name);
                strcat_s(redTeam, sizeof(redTeam), " ");
                numPlayer2++;
                break;
            }
            strcat_s(blueTeam, sizeof(blueTeam), name);
            strcat_s(blueTeam, sizeof(blueTeam), " ");
            numPlayer1++;
        } else {
            if (numPlayer2 == 8) {
                strcat_s(blueTeam, sizeof(blueTeam), name);
                strcat_s(blueTeam, sizeof(blueTeam), " ");
                numPlayer1++;
                break;
            }
            strcat_s(redTeam, sizeof(redTeam), name);
            strcat_s(redTeam, sizeof(redTeam), " ");
            numPlayer2++;
        }
    }
    printf("\nBlue team : %s.\n", blueTeam);
    printf("\nRed team : %s.\n", redTeam);
    return 0;
}