Here's a C++ program that counts the occurrences of each character in a given string:
cpp#include <iostream>
#include <map>
int main() {
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString);
std::map<char, int> characterCount;
for (char character : inputString) {
// Ignore whitespace characters
if (!std::isspace(character)) {
characterCount[character]++;
}
}
std::cout << "Character occurrences:" << std::endl;
for (const auto& entry : characterCount) {
std::cout << "'" << entry.first << "': " << entry.second << " times" << std::endl;
}
return 0;
}
Explanation:
- 1. The program uses a
std::map
namedcharacterCount
to store the counts of each character in the input string. - 2. The program first takes an input string from the user using
std::getline
, which allows for reading a complete line of text. - 3. The program then iterates through each character in the input string.
- 4. Inside the loop, whitespace characters (like spaces or tabs) are ignored using the
std::isspace
function. - 5. The non-whitespace characters are inserted into the
characterCount
map, and their counts are incremented. - 6. After processing all characters, the program prints out the occurrences of each character.
- 7. The
for
loop iterates through thecharacterCount
map and prints the character and its corresponding count.
For example, if the user inputs "hello world"
, the output might be:
cppEnter a string: hello world
Character occurrences:
'h': 1 times
'e': 1 times
'l': 3 times
'o': 2 times
'w': 1 times
'r': 1 times
'd': 1 times
In this example, the program counts and displays the occurrences of each character in the input string, while ignoring whitespace characters.