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