C: Use two gets() in a row (player names)?

Asked

Viewed 334 times

0

I’m trying to play a little game, so I displayed a menu and then I used the command switch to access the options, in case the user wants to play he selects 1 and will be asked to him the name of players 1 and 2, for this I used the getbut when I run the code it jumps player 1 and goes directly to player 2, how do I fix it? I am using so:

printf("Nome do Player1: ");
gets(player);
printf("\n");
printf("Nome do Player2: ");
gets(pl2); 

NOTE: I correctly declared the vectors, and these codes are within the case 1 of switch

2 answers

1


Do not use the get he is not very safe and gives enough trouble with the buffer, a good alternative is the scanf.

Example:

printf("Nome do Player1: ");
scanf("%s", &player);
printf("\n");
printf("Nome do Player2: ");
scanf("%s", &pl2);

If you want, there’s fgets take a look here.

  • Opa, I did not know that the scanf worked in this case, already helped a lot, thanks, fgets is a little complicated and does not cover this work I’m doing, so the way is to use the scanf.. Thank you

  • @Leonardovilarinho If you solved your problem, mark the answer as the solution, good night! :)

  • I marked there already..

1

I would be even more reticent about the indiscriminate use of scanf. In particular, this same scanf("%s",&p) may be targeted at buffer overflow. It would be important to limit the size of the received string: scanf("%100s",&p).

(As a matter of fact, I’m an even bigger cunt about scanf; I prefer to create own versions using getc and putc.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.