Aryan Soni
Aryan Soni

Reputation: 76

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 -

Enter a string: Aryan
Length of the string = 6
Process returned 0 (0x0)   execution time: 4.372 s
Press any key to continue.

Upvotes: 2

Views: 420

Answers (2)

DevSolar
DevSolar

Reputation: 70372

The fgets() call includes the newline read from the input stream. This is useful, because it allows you to check if the line was read completely. If the input did not have a newline as last character, then the line read was incomplete.

int main()
{
    char a[MAX];
    size_t len;   // being precise with your types is a good habit
    printf("Enter a string: ");
    fgets(a, MAX, stdin);

    len = strlen(a);

    if ( a[len - 1] == '\n' )
    {
        // Usually you don't want the newline in there.
        a[--len] = '\0';
        // --len above corrected the length.
        printf("Length of the string = %zu\n", len);
    }
    else
    {
        printf("Length of the string longer than %d\n", MAX - 1);
        // You can repeat fgets() until you get the whole line,
        // or keep reading (and throwing away) from input until
        // you get a newline. It really depends on how you want
        // to handle the error.
    }

    return 0;
}

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

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';

Upvotes: 9

Related Questions