1
0

wordcnt.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // wordcnt.c -- counts characters, words, lines
  2. #include <stdio.h>
  3. #include <ctype.h> // for isspace()
  4. #include <stdbool.h> // for bool, true, false
  5. #define STOP '|'
  6. int main(void)
  7. {
  8. char c; // read in character
  9. char prev; // previous character read
  10. long n_chars = 0L; // number of characters
  11. int n_lines = 0; // number of lines
  12. int n_words = 0; // number of words
  13. int p_lines = 0; // number of partial lines
  14. bool inword = false; // == true if c is in a word
  15. printf("Enter text to be analyzed (| to terminate):\n");
  16. prev = '\n'; // used to identify complete lines
  17. while ((c = getchar()) != STOP)
  18. {
  19. n_chars++; // count characters
  20. if (c == '\n')
  21. n_lines++; // count lines
  22. if (!isspace(c) && !inword)
  23. {
  24. inword = true; // starting a new word
  25. n_words++; // count word
  26. }
  27. if (isspace(c) && inword)
  28. inword = false; // reached end of word
  29. prev = c; // save character value
  30. }
  31. if (prev != '\n')
  32. p_lines = 1;
  33. printf("characters = %ld, words = %d, lines = %d, ",
  34. n_chars, n_words, n_lines);
  35. printf("partial lines = %d\n", p_lines);
  36. return 0;
  37. }