count word accurances in a string c++
#include <iostream>
#include <sstream>
#include <map>
int main() {
std::string input;
std::getline(std::cin, input);
std::istringstream iss(input);
std::map<std::string, int> wordCount;
std::string word;
while (iss >> word) {
// Remove punctuation (if needed) and convert to lowercase
// For simplicity, assuming each word is separated by spaces
// Modify this part based on your specific requirements
// Increment the count for the current word
wordCount[word]++;
}
// Output the word occurrences
for (const auto& pair : wordCount) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
Explanation:
1. Include necessary headers for input/output, string manipulation, and mapping data structure.
2. Declare a string variable (input
) to store the input sentence.
3. Use std::getline
to read a line of input from the user and store it in the input
variable.
4. Create an std::istringstream
object (iss
) to stream the input string.
5. Declare a std::map
named wordCount
to store word occurrences.
6. Declare a string variable (word
) to store individual words while iterating through the input.
7. Use a while
loop to iterate through each word in the input stream.
8. Inside the loop, perform any necessary pre-processing (e.g., removing punctuation, converting to lowercase).
9. Increment the count for the current word in the wordCount
map.
10. After processing all words, use a loop to output the word occurrences from the wordCount
map.
11. The program returns 0 to indicate successful execution.