Final answer:
To count the number of times a character appears in a string in C++, you can iterate through each character and compare it to the given character. If there is a match, increment a counter variable. Finally, output the count.
Step-by-step explanation:
To count the number of times a character appears in a string using C++, you can iterate through each character in the string and compare it to the given character. If there is a match, you increment a counter variable. Here's an example of how you can implement this:
#include <iostream>
#include <string>
int main() {
char character;
std::string input;
int count = 0;
std::cout << "Enter a character: ";
std::cin >> character;
std::cout << "Enter a string: ";
std::cin.ignore();
std::getline(std::cin, input);
for (char c : input) {
if (c == character) {
count++;
}
}
std::cout << "The character " << character << " appears " << count << " times in the string." << std::endl;
return 0;
}
In this code, we use a for-each loop to iterate through each character of the input string. If the character matches the given character, we increment the count variable. Finally, we output the number of times the character appears in the string.