C reads wrong amount of strings

P. Bolfa Source

I am trying to read 3 strings (3 lines) where the first line - cards of player 1 , the second line - cards of player 2 , the third line - cards in the deck. The problem is that C only reads the first two lines and skip reading the deck. `

 char firstPlayerCards [5];
 char secondPlayerCards [5];
 char deck [14];
 fgets(firstPlayerCards, sizeof(firstPlayerCards),stdin);
 fgets(secondPlayerCards, sizeof(secondPlayerCards),stdin);
 fgets(deck, sizeof(deck),stdin);

Input is like:

5h 5d
7h As
2h 8d 4h Jh Ah


answered 7 days ago David K #1

You need larger arrays.

Each player's hand is 5 characters, which should be stored in 5 bytes plus one byte to hold a null terminator. So you need at least 6 bytes in each array to hold the hands.

fgets helpfully only reads 4 bytes when you call it like fgets(firstPlayerCards, 5, stdin) in order to avoid undefined behavior when it writes the null character. So you are not reading the input that you intended to.

answered 7 days ago achal #2

Make sure firstPlayerCards and secondPlayerCards have enough memory to store user input string. As you shown the example input, 5h 5d having 5 char plus new line and you declare firstPlayerCards of only 5 char, change it to 7.

from the manual page of fgets()

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

for example

char firstPlayerCards [5];
fgets(firstPlayerCards, sizeof(firstPlayerCards),stdin); /* it reads only 4 char as fgets() reads size minus one char from stream, if you want to read all char or more change the size of array */

comments powered by Disqus