Home > Enterprise >  while counting length of a string I'm trying to scan input with the help of fgets() but it isn&
while counting length of a string I'm trying to scan input with the help of fgets() but it isn&

Time:10-22

When I am using gets() to scan input it is working perfectly ,but when I'm using fgets() to scan the input then the answer is coming out as 1 more than the actual length. For example:--> For input "Hello" fgets() is printing 6. BUT the answer should be 5. Why? How to resolve

#include <stdio.h>
#include <string.h> 

int string_length(char str[]);

int main()
{
    char str[100];
    printf("**********************************************\n");
    printf("This is a program to reverse a string.\n");
    printf("**********************************************\n");
    printf("Enter a string: ");
    fgets(str,100,stdin);  // ----> when using this fgets() answer of length of string is coming out to be one more than the actual answer
    gets(str); //This is giving the correct answer if used instead of fgets().

    printf("%d",string_length(str));

    return 0;
}

//function for calculating string length
int string_length(char str[])
{
    int i;
    for(i=0; str[i]!='\0'; i  );
    return i;


    //WAY__2
    //OR by while loop
    // int i,length=0;
    // while (str[length] != '\0')
    // {
    //     length   ;
    // }
    // return length;


    //WAY__3
    //OR by using strlen() function;
    // int length = strlen(str);
    // return length;

}

CodePudding user response:

The function fgets can append the new line character '\n' to the entered sequence of characters. You should remove it as for example

str[ strcspn( str, "\n" ) ] = '\0';

As for the function gets then it is unsafe and is not supported by the C Standard. You should not use it.

As for your function string_length then it should be declared like

size_t string_length( const char str[] );

CodePudding user response:

fgets reads also \n character from the file/stream. You need to remove it.

char *removeNL(char *str)
{
    char *wrk = str;
    if(wrk) 
    {
        while(*wrk && *wrk != '\n' ) wrk  ;
        *wrk = 0;
    }
    return str;
}

Also use the correct type for sizes (size_t)

size_t string_length(const char *str)
{
    size_t i;
    for(i=0; str[i]!='\0'; i  );
    return i;
}

You do not need the counter as you can use the pointer arithmetic to get the string length:

size_t string_length1(const char *str)
{
    const char *end = str;
    while(*end) end  ;
    return end - str;
}
  • Related