简体   繁体   中英

Why does fgets function in the program below (see detail) interprets the length of string by one extra character?

Here is the source code with gets function:

//Finding length of a string//
#include<stdio.h>
#include<conio.h>
int main()
{
    //Finding length by user written code//
    int i=0;
    char ar[200];
    printf("So enter your string here: ");
    gets(ar);
    while(ar[i]!='\0')
        i++;
    printf("The length of your string is: %d",i);
    getch();
    return 0;
}

Here are the input and output:

So enter your string here: Hello World
The length of your string is: 11

But if the gets function is replaced by fgets function, that is if the code is written as:

//Finding length of a string//
#include<stdio.h>
#include<conio.h>
int main()
{
    //Finding length by user written code//
    int i=0;
    char ar[200];
    printf("So enter your string here: ");
    fgets(ar,200,stdin);
    while(ar[i]!='\0')
        i++;
    printf("The length of your string is: %d",i);
    getch();
    return 0;
}

Then input and output become:

So enter your string here: Hello World
The length of your string is: 12

So, why is fgets function giving the length by one extra character?

It is because fgets stores a \\n character before adding the null-terminating \\0 .

from cppreference fgets

... Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

and from cppreference gets

The newline character, if found, is discarded and does not count toward the number of characters written to the buffer.

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