我刚刚开始使用C语言,因为我的大学有一些编程课程。当我们在Dev C ++程序中编程时,我从高中知道一点C。现在我们需要使用Visual Studio,我编写的下一个程序在Dev C ++中工作正常,但在输入名称后崩溃了。在开发C ++中,我从_s
和strcat
中删除了scanf
,它完美无缺。有人可以帮我解决这个问题吗?这个程序是关于输入一个名字,它应该随机设置你在这两个团队中的一个。
#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;
}
答案 0 :(得分:1)
scanf_s
和scanf
的语义略有不同:对于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;
}