Trying to write a C program that:
counts the number of characters, words and lines read from standard input until EOF is reached. Assume the input is ASCII text of any length. Words are defined as contiguous sequences of letters (a through z, A through Z) and the apostrophe ( ', value 39 decimal) separated by any character outside these ranges. Lines are defined as contiguous sequences of characters separated by newline characters ('\n'). Characters beyond the final newline character will not be included in the line count.
I have written the following, which works fine to count the characters, but does not count any of the words or lines. I don't understand why.
#include <stdio.h>
int main() {
unsigned long int countchar=0;
unsigned long int word=0;
unsigned long int line=0;
int c;
while (((c=getchar())!=EOF)) {
countchar++;
if ((c>='A' && c<= 'Z') || (c>='a' && c<= 'z') || (c==39)) {
word++;
}
else if (c=='\n') {
line++;
}
}
printf("%lu %lu %lu\n", countchar, word, line);
return 0;
}
You are counting each letter in a word as a word. It should work to change it to check that it isn't any of the letters in words and remove the else. You might need to add some extra checks so that you only increase words if the last letter was in a word.
if (!((c>='A' && c<= 'Z') || (c>='a' && c<= 'z') || (c==39)) {
word++;
}
if (c=='\n') {
line++;
}