Below is a simple C++ program that prompts the user to enter a string and then utilizes two functions: one for printing each word and another for counting the total number of words. We'll manage the string using C-style strings (character arrays). Please note that this program assumes that words are separated by spaces and does not handle punctuation or other word delimiters.
#include <iostream>
#include <cstring> // for strlen, strtok
// Function prototypes
void printWords(const char* str);
int countWords(const char* str);
int main() {
const int MAX_STRING_LENGTH = 1000; // Define maximum length of the string
char inputStr[MAX_STRING_LENGTH]; // Initialize a C-string (char array) to hold the input
// Prompt the user for input
std::cout << "Please enter a string: ";
std::cin.getline(inputStr, MAX_STRING_LENGTH); // Read a line of input into the char array
// Print and count the words
printWords(inputStr);
int wordCount = countWords(inputStr);
std::cout << "Total number of words: " << wordCount << std::endl;
return 0;
}
void printWords(const char* str) {
int length = strlen(str);
char copyStr[length + 1]; // Create a copy to avoid modifying the original string
strcpy(copyStr, str); // Copy the input string to prevent strtok from modifying it
// Tokenize and print each word
char* token = strtok(copyStr, " "); // Extract the first word
while (token != NULL) { // Continue until there are no more words
std::cout << token << std::endl; // Print the current word
token = strtok(NULL, " "); // Get the next word
}
}
int countWords(const char* str) {
if (strlen(str) == 0) // If string is empty return 0
return 0;
int count = 0;
bool inWord = false; // Keeps track of whether we're currently inside a word
for (int i = 0; str[i] != '\0'; ++i) { // Iterate over each character
if (str[i] != ' ' && !inWord) { // A new word starts
inWord = true; // We are now inside a word
count++; // Increment the word count
} else if (str[i] == ' ' && inWord) { // Word ends
inWord = false; // We are now outside of a word
}
}
return count;
}
This program uses getline to read a line of input into a char array, ensuring the user can enter a string of variable length up to the defined maximum. It includes two separate functions printWords and countWords, which use strtok and a simple loop with a boolean flag, respectively, to handle word parsing and counting.
Please note that strtok modifies the string it processes, hence we first create a copy of the input string (using strcpy) in printWords to avoid issues with subsequent operations on the original string. This is not required within the countWords function because it doesn't utilize strtok.
When you compile and run this program, make sure to test it with different cases, including strings with multiple spaces between words and strings with leading or trailing spaces.