I am running this code using C to count the words in char array, but somehow it keeps counting the total characters + 1.
Any solution to fix this problem?
#include <stdio.h>
int main()
{
char input[1001];
int count =0;
fgets(input, 1001, stdin);
char *array = input;
while(*array != '\0')
{
if(*array == ' '){
array++;
}
else{
count++;
array++;
}
}
printf("this character's length is %d.", count);
printf("this characterarray : %s", input);
return 0;
}
Thank you for the question.
Here is the catch !!
When ever you are using fgets() function, it also stores the newline character into the string.
So if the string entered is "abc" and then you hit the Enter key , the array will store the string as 'a','b','c','\n','\0' . So you can see total characters is 4 and not 3
So you need to decrement the count by 1 after the while loop ends. I have updated the code and it works fine now.
thank you
======================================================================================
#include <stdio.h>
int main()
{
char input[1001];
int count =0;
fgets(input, 1001, stdin);
char *array = input;
while(*array != '\0')
{
// dont count white space line feed or new line
characters
if(*array == ' ' || *array=='\n' || *array=='\r'){
array++;
}
else{
count++;
array++;
}
}
printf("this character's length is %d.", count);
printf("this characterarray : %s", input);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.