fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <cctype>
  5.  
  6. std::istringstream in(
  7. "Hi all,\n"
  8. "\n"
  9. "I would like to write a program to count the number of characters, "
  10. "words, and paragraphs(or newlines) in a file.I have the characters "
  11. "counting correctly and the newlines counting correctly but I am "
  12. "stuck on how to count the words, I would like to store the words in "
  13. "an array to hold the size of the word(i.e.the number of letters "
  14. "influences where its stored in the array) then I need to sum up the "
  15. "array and display the output.\n"
  16. "\n"
  17. "Thanks in advance for the help."
  18. );
  19.  
  20. int main()
  21. {
  22. std::size_t characters = 0;
  23. std::size_t words = 0;
  24. std::size_t paragraphs = 0;
  25.  
  26. bool in_word = false;
  27. bool in_paragraph = false;
  28.  
  29. char token;
  30. while (in.get(token))
  31. {
  32. if (std::isspace(token))
  33. { // whitespace
  34. in_word = false;
  35.  
  36. if (token == '\n')
  37. in_paragraph = false;
  38. }
  39. else
  40. { // non-whitespace
  41. ++characters;
  42.  
  43. if (!in_paragraph)
  44. {
  45. in_paragraph = true;
  46. ++paragraphs;
  47. }
  48.  
  49. if (!in_word)
  50. {
  51. in_word = true;
  52. ++words;
  53. }
  54. }
  55. }
  56.  
  57. std::cout << "Characters:" << std::setw(5) << characters << '\n';
  58. std::cout << "Words: " << std::setw(5) << words << '\n';
  59. std::cout << "Paragraphs:" << std::setw(5) << paragraphs << '\n';
  60. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Characters:  381
Words:        87
Paragraphs:    3