Iam doing skillrack challenges for more than a year now my question is when i execute the following program iam getting 6 and 5, instead of 5 5 for the input:
bell
hell
(Iam getting correct output when i execute this in netbeans ide but what is the problem with skillrack site ide. Please correct if my program contains any error)
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[1000];
char str2[1000];
int s1,s2;
fgets(str1,1000,stdin);
fgets(str2,1000,stdin);
s1=strlen(str1);
s2=strlen(str2);
printf("%d\n%d",s1,s2);
}
In my point of view i think they have added spaces at the end of each string. If thats the case how to find the length of the string without taking spaces into account.
In my point of view i think they have added spaces at the end of each string. If thats the case how to find the length of the string without taking spaces into account.
The fgets() function will also include the newline character '\n' as part of the string, hence the value 5 rather than 4 for a string such as "bell\n"
As an different idea, instead of using fgets(), you might consider fscanf()
IN addition to being unsafe, fgets() is a real pain to use reliably. As Chervil points out, you usually want to remove the trailing \n. But you always have to check if it's there because the last line in the file might not end in a newline.