Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this C program to calculate string's length give a wrong output?

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading