Search code examples
carraysstringcharfgets

fgets() not scanning the number of strings I want


I have an array of sentences and I want to scan them first with fgets() and then print them one by one. Here is the program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>





int main(int argc,char *argv[]) {

    char sentence[100][100]; /* 100 sentences with at most 100 characters*/
    int n,i,j;

    scanf("%d",&n); /* number of sentences*/

    for (i=0;i<n;i++) {
        fgets(sentence[i],100,stdin);
    }
    printf("****************************");
    for (i=0;i<n;i++) {
        for(j=0;j<strlen(sentence[i]);j++) {
            putchar(sentence[i][j]);
        }

    }


    return 0;
}

The problem is that this only scans n-1 sentences. Why is that?

And the other weird thing is that after printing the asterisks, it starts printing at a new line without me telling it to do so.


Solution

  • Assume the input is

    3
    abc
    def
    ghi
    

    The cursor stays after the number 3 on the first line after n is scanned.

    You can add a space after %d, like scanf("%d ", &n); to move the cursor to the next line. (This assumes that the first sentence does not start with spaces).

    Depends on whether your environment is (Windows / Unix), and whether you want every string to keep the end of line character, you need to increase the buffer size to:

    • 101 - for Unix line ending and you are fine to discard the end of line character for sentences of 100 characters long
    • 102 - for Windows line ending and you are fine to discard the end of line character for sentences of 100 characters long
    • 102 - for Unix line ending and you want to keep the end of line character for all sentences
    • 103 - for Windows line ending and you want to keep the end of line character for all sentences

    For example, if you incorrectly used 101 for Windows, for the following input

    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    

    The output would be:

    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    
    
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
    
    
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

    (there are some empty lines)