简体   繁体   中英

How fgets treats \n?

I have written the below code to sort strings in alphabetical order.But I m unable to understand how fgets is working here.

#include<stdio.h>
#include<string.h>
int main()
{
    char s[10][15];
    int n;
    printf("enter the no of names\n");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
       fgets(s[i],15,stdin);
       //scanf("%s",s[i]);
    }
    for(int i=1;i<n;i++)
    {
        for(int j=0;j<n-i;j++)
            if(strcmp(s[j],s[j+1])>0)
        {
            char g[15];
            strcpy(g,s[j]);
            strcpy(s[j],s[j+1]);
            strcpy(s[j+1],g);
        }
    }
    printf("the sorted strings are");
    for(int i=0;i<n;i++)
        printf("%s",s[i]);
    return 0;
}

If I use scanf instead of fgets to accept strings, n words are accepted but when I'm using fgets for same purpose instead of scanf , n-1 words are accepted. Why is it so?

Is fgets placing last newline character in the n th place?

This is what happens when you mix fgets and scanf calls in the same program.

You start out using scanf to read the number of names. This reads a number and leaves a newline in the input buffer. When you then go into your loop and call fgets for the first time it reads that newline in the buffer immediately and then goes to the next iteration of the loop, calling fgets again.

When you use scanf in the loop instead, the %s format specifier first reads and discards and whitespace characters, which includes the newline from the prior scanf call.

If you still want to use fgets , you first need to clear the input buffer prior to the loop by calling getchar until you read a newline. Also, keep in mind that fgets includes the newline in the string it reads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM