If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To count the number of words and vowels in a string, you can use simple iteration and conditional checks. Here's a C++ program that demonstrates how to count words and vowels in a given string:
cppCopy code
#include <iostream> #include <string> #include <cctype> int countWords(const std::string& str) { int wordCount = 0; bool inWord = false; for (char c : str) { if (std::isalpha(c)) { if (!inWord) { inWord = true; wordCount++; } } else { inWord = false; } } return wordCount; } int countVowels(const std::string& str) { int vowelCount = 0; const std::string vowels = "aeiouAEIOU"; for (char c : str) { if (vowels.find(c) != std::string::npos) { vowelCount++; } } return vowelCount; } int main() { std::string inputString; std::cout << "Enter a string: "; std::getline(std::cin, inputString); int wordCount = countWords(inputString); int vowelCount = countVowels(inputString); std::cout << "Number of words: " << wordCount << std::endl; std::cout << "Number of vowels: " << vowelCount << std::endl; return 0; }In this program, we define two functions:
countWordsandcountVowels. ThecountWordsfunction iterates through the characters of the input string and counts the number of words. It considers a word as a continuous sequence of alphabetic characters.The
countVowelsfunction iterates through the characters of the input string and counts the number of vowels (both lowercase and uppercase).The
main()function takes user input for the string, and then calls thecountWordsandcountVowelsfunctions to calculate the word count and vowel count, respectively.Sample Input:
cCopy code
Enter a string: Hello, how are you?Sample Output:
javascriptCopy code
Number of words: 4 Number of vowels: 6This program provides a straightforward way to count the number of words and vowels in a given string.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support