fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <ctype.h>
  4.  
  5. using namespace std;
  6.  
  7. int word_count, letter_count;
  8.  
  9. bool get_word()
  10. {
  11. char c;
  12.  
  13. // skip all characters except for letters and new-line
  14. while (cin.get(c) && !isalpha(c) && '\n' != c)
  15. ;
  16.  
  17. // did we reach the end of line?
  18. if (!cin || '\n' == c)
  19. return false; // we read all the words
  20.  
  21. //
  22. string word{ c }; // add the first read character to word
  23. while (cin.get(c) && isalpha(c)) // while the read character is a letter add it to the word
  24. word += c;
  25.  
  26. // the last read character is not a letter, so put it back in stream
  27. cin.putback(c);
  28.  
  29. // now we have a word: count it
  30. ++word_count;
  31.  
  32. // count letters in word
  33. letter_count += word.length();
  34.  
  35. // we still have words to read
  36. return true;
  37. }
  38.  
  39. int main()
  40. {
  41. while (get_word())
  42. ;
  43.  
  44. cout
  45. << "words: " << word_count << endl
  46. << "letters: " << letter_count;
  47. }
  48.  
  49.  
Success #stdin #stdout 0s 4500KB
stdin
Hello, world!
stdout
words: 2
letters: 10