I have written this program which accepts a string as an input and return the length of it.
#include<stdio.h>
#include<string.h>
#define MAX 100
int main()
{
char a[MAX];
int len;
printf("Enter a string: ");
fgets(a, MAX, stdin);
len = strlen(a);
printf("Length of the string = %d", len);
return 0;
}
Since the function strlen() doesn’t count null character i.e. '\0', why is my output always 1 more than the characters of input string?
For Example –
Enter a string: Aryan
Length of the string = 6
Process returned 0 (0x0) execution time: 4.372 s
Press any key to continue.
>Solution :
The function fgets can append to the entered string the new line character '\n' if there is a space in the supplied array.
From the C Standard (7.21.7.2 The fgets function)
2 The fgets function reads at most one less than the number of
characters specified by n from the stream pointed to by stream into
the array pointed to by s. No additional characters are read after a
new-line character (which is retained) or after end-of-file. A null
character is written immediately after the last character read into
the array
Thus in this call of strlen
len = strlen(a);
the new line character is also counted.
You need to remove it as for example
a[ strcspn( a, "\n" ) ] = '\0';
or
char *p = strchr( a, '\n' );
if ( p != NULL ) *p = '\0';