trying to write a program using a while loop to count words chars and lines.......everything works except for multiple spaces. Any help would be much appreciated. Sincere thanks.
Dwight Gooden
#include "stdio.h"
int main()
{
char c;
int characters=0;
int lines=0;
int words=0;
char nc;
char lc;;
while((c=getchar()) !=EOF)
{
nc=++c;
if (c!=' ' && c!='\n')
{
++characters;
}
if (c=='\n')
{
++lines;
}
if ((c==' ')&& (nc!=' ') ||(c=='\n'))
{
++words;
}
}
printf("number of characters is %d, number of words is %d, number of lines is %d",characters,words,lines);
}
I will give these suggestions to this. First think about the problem. characters are every character that comes in to an end of line, which includes spaces and not the end of line.
Words are a count of characters between spaces and end of line.
simple algorithm is:
while we get get characters from the stream, we count the characters blindly. After we count the character, we do some checking and we want to know if its not a space or a end of line(\n), we want to increment the word length counter. If it is a space or an end of line, we want to check the word length for it is not zero. If it is some value other than zero we want to increment the word count by 1 then clear the word length to zero. If the word length is zero we don't count the word, or in other words the double space. Line count is incrementing the line count on the '\n' which I would check for before I counted the character.