Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

What wrong with this simple code??

0 votes
asked May 28, 2020 by Bill Fischer (120 points)
char buf[16];

   
    printf("Enter the first string: ");
    
    fgets(buf, 16, stdin);
    printf("%s", buf);
    printf("Enter the second stringl: ");
    fgets(buf, 16, stdin);
    printf("%s", buf);

Prinf the first message, then SKIPS the first fgets.

printf the second message and stops awaiting input on  the second fgets

2 Answers

–1 vote
answered May 29, 2020 by Peter Minarik (86,040 points)

http://www.cplusplus.com/reference/cstdio/fgets/

fgets copies the first num characters (including the '\0' at the end). If there are more on the stream, it ignores them.

So if you enter more than 15 characters, the first time you call fget(buf, 16, stdin) it will remove the first 15 characters from the SDTIN, and leave the rest there.

Hence, calling it for the second time, STDIN is not empty, and therefore there is no prompt for the user to enter anything. It just keeps reading the rest of the (not yet processed) characters from STDIN.

+1 vote
answered May 29, 2020 by LiOS (6,420 points)
edited May 30, 2020 by LiOS
The code works fine if you enter a string of 15 characters or less. However, if you enter more than 15 characters, the second fgets reads from the stdin where there are characters still there from the previous string read and will take those, skipping the request for input.

To solve this, since you don't know how much input the user do and in C you can't make an array of an unitialised value that automatically changes the size based on the input, unlike other languages, you'll need to create a pointer to a string where a byte is allocated for each character inputted, making sure to add \0 at the end.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...