I just started a while ago with C language because my University has a few programming lessons. I knew a little of C from High School when we were programming it in Dev C++ program. Now we need to use Visual Studio for it and next program I wrote works fine in Dev C++ but crashes after entering name. In dev C++ I remove _s from strcat and scanf and it works perfect. Can somebody help me with this problem ? This program is about entering a name and it should randomly set you in one of those two teams.
#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_s and scanf have slightly different semantics: for s and [ formats, you must pass the size of the destination array:
scanf_s(" %s", name, sizeof(name));
Similarly, strcat_s takes as a third argument between the destination array and the source string, the count of elements in the destination array.
Here is a modified version of your code:
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With