Use fgets and strlen to calculate the length of a txetstring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
 
int main()
{
    char input[256];
    char buffer[256];
    int length;
   // gets(buffer);
    fgets(buffer, 256, stdin);
    length=strlen(buffer);
    printf("%s\n",buffer);
    printf("length=%d\n",length);
    return 0;

}


The output of this short program is really weird.When I type 123 from the keyboard,I get the following answer in console window"123 length=4".Why the output of length is always 1 more than the actual length of the string that I type in.
Last edited on
However,if I use gets to take input from the keyboard,I get the right length,which is 3 in this case.
Last edited on
When you use fgets and hit "Enter", a newline charater is included at end of your buffer.
Topic archived. No new replies allowed.