One improvement would be to handle lines that contain multiple spaces between words or tabs, while still considering a simple return '\n' as a word. Using getline provides a number of advantages including providing the number of characters read. Here is an example of the approach:
Edit logic simplified:
#include <stdio.h>
int main (void) {
char *line = NULL; /* pointer to use with getline () */
char *p = NULL; /* pointer to parse getline return */
ssize_t read = 0;
size_t n = 0;
int spaces = 0; /* counter for spaces and newlines */
int total = 0; /* counter for total words read */
printf ("\nEnter a line of text (or ctrl+d to quit)\n\n");
while (printf (" input: ") && (read = getline (&line, &n, stdin)) != -1) {
spaces = 0;
p = line;
if (read > 1) { /* read = 1 covers '\n' case (blank line with [enter]) */
while (*p) { /* for each character in line */
if (*p == '\t' || *p == ' ') { /* if space, */
while (*p == '\t' || *p == ' ') /* read all spaces */
p++;
spaces += 1; /* consider sequence of spaces 1 */
} else
p++; /* if not space, increment pointer */
}
}
total += spaces + 1; /* words in line = spaces + 1 */
printf (" chars read: %2zd, spaces: %2d total: %3d line: %s\n",
read, spaces, total, (read > 1) ? line : "[enter]\n");
}
printf ("\n\n Total words read: %d\n\n", total);
return 0;
}
output:
Enter a line of text (or ctrl+d to quit)
input: my
chars read: 3, spaces: 0 total: 1 line: my
input: dog has
chars read: 8, spaces: 1 total: 3 line: dog has
input: fleas and ticks
chars read: 17, spaces: 2 total: 6 line: fleas and ticks
input:
chars read: 1, spaces: 0 total: 7 line: [enter]
input:
chars read: 1, spaces: 0 total: 8 line: [enter]
input: total_words 10
chars read: 17, spaces: 1 total: 10 line: total_words 10
input:
Total words read: 10
one twogcc -Wall -g). Also, don't usegetsbutfgets. At last learn right now how to use the debuggergets(), butfgets, you may also use\nas a word delimiter.Hello, I am ... John-F Kennedy!as an input.