fork download
  1. //OrinTill Qimid CS1A Chapter 4, P. 294, 10
  2. //
  3. /**************************************************************
  4.  * Word Counter
  5.  *
  6.  * ____________________________________________________________
  7.  * This program will count the words entered.
  8.  * ____________________________________________________________
  9.  * INPUT
  10.  * Entered words
  11.  * OUTPUT
  12.  * Ho many words was counted.
  13.  **************************************************************/
  14. #include <iostream>
  15. #include <iomanip>
  16. #include <cmath>
  17. using namespace std;
  18.  
  19. #include <iostream>
  20. #include <cstring> // For strlen and strtok
  21. #include <string> // For std::string
  22.  
  23. using namespace std;
  24.  
  25. // Function to count words in a C-string
  26. int countWords(const char* str) {
  27. int count = 0;
  28. bool inWord = false;
  29.  
  30. for (int i = 0; str[i] != '\0'; i++) {
  31. if (isspace(str[i])) {
  32. if (inWord) {
  33. inWord = false;
  34. }
  35. } else {
  36. if (!inWord) {
  37. count++;
  38. inWord = true;
  39. }
  40. }
  41. }
  42.  
  43. return count;
  44. }
  45.  
  46. // Overloaded function to count words in an std::string
  47. int countWords(const string& str) {
  48. int count = 0;
  49. bool inWord = false;
  50.  
  51. for (char ch : str) {
  52. if (isspace(ch)) {
  53. if (inWord) {
  54. inWord = false;
  55. }
  56. } else {
  57. if (!inWord) {
  58. count++;
  59. inWord = true;
  60. }
  61. }
  62. }
  63.  
  64. return count;
  65. }
  66.  
  67. int main() {
  68. const int SIZE = 256; // Maximum buffer size for C-string
  69. char cString[SIZE];
  70. string stdString;
  71.  
  72. // Get input as a C-string
  73. cout << "Enter a string (C-string): ";
  74. cin.getline(cString, SIZE);
  75.  
  76. // Call the function for C-string
  77. int cStringWordCount = countWords(cString);
  78. cout << "The number of words in the C-string: " << cStringWordCount << endl;
  79.  
  80. // Get input as a std::string
  81. cout << "Enter a string (string): ";
  82. getline(cin, stdString);
  83.  
  84. // Call the overloaded function for std::string
  85. int stdStringWordCount = countWords(stdString);
  86. cout << "The number of words in the string: " << stdStringWordCount << endl;
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Standard output is empty