//OrinTill Qimid CS1A Chapter 4, P. 294, 10
//
/**************************************************************
* Word Counter
*
* ____________________________________________________________
* This program will count the words entered.
* ____________________________________________________________
* INPUT
* Entered words
* OUTPUT
* Ho many words was counted.
**************************************************************/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
#include <iostream>
#include <cstring> // For strlen and strtok
#include <string> // For std::string
using namespace std;
// Function to count words in a C-string
int countWords(const char* str) {
int count = 0;
bool inWord = false;
for (int i = 0; str[i] != '\0'; i++) {
if (isspace(str[i])) {
if (inWord) {
inWord = false;
}
} else {
if (!inWord) {
count++;
inWord = true;
}
}
}
return count;
}
// Overloaded function to count words in an std::string
int countWords(const string& str) {
int count = 0;
bool inWord = false;
for (char ch : str) {
if (isspace(ch)) {
if (inWord) {
inWord = false;
}
} else {
if (!inWord) {
count++;
inWord = true;
}
}
}
return count;
}
int main() {
const int SIZE = 256; // Maximum buffer size for C-string
char cString[SIZE];
string stdString;
// Get input as a C-string
cout << "Enter a string (C-string): ";
cin.getline(cString, SIZE);
// Call the function for C-string
int cStringWordCount = countWords(cString);
cout << "The number of words in the C-string: " << cStringWordCount << endl;
// Get input as a std::string
cout << "Enter a string (string): ";
getline(cin, stdString);
// Call the overloaded function for std::string
int stdStringWordCount = countWords(stdString);
cout << "The number of words in the string: " << stdStringWordCount << endl;
return 0;
}