216k views
2 votes
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string.

Ex: If the input is:

n Monday
the output is:

1
Ex: If the input is:

z Today is Monday
the output is:

0
Ex: If the input is:

n It's a sunny day
the output is:

2
Case matters.

Ex: If the input is:

n Nobody
the output is:

0
n is different than N.





This is what i have so far.
#include
#include
using namespace std;

int main() {

char userInput;
string userStr;
int numCount;

cin >> userInput;
cin >> userStr;

while (numCount == 0) {
cout << numCount << endl;
numCount = userStr.find(userInput);

}
return 0;
}

User ZimZim
by
5.8k points

1 Answer

5 votes

Final answer:

The student's programming task is to count the number of times a character appears in a string. The initial code provided has some issues, and a revised version with a proper counting loop has been provided. The solution ensures that the character count is accurate and satisfies the case sensitivity requirement.

Step-by-step explanation:

The program you're working on aims to count the number of times a specified character appears within a given string. To accomplish this, you need to initialize the numCount variable and utilize a loop to iterate over the provided string rather than using the find method. Let's revise your code to properly count the character occurrences.

Revised Program Code:

#include <iostream>
#include <string>
using namespace std;

int main() {
char userInput;
string userStr;
int numCount = 0; // Initialize the count variable

cin >> userInput;
getline(cin >> ws, userStr); // Read the entire line for the string

for(char c : userStr) { // Iterate over each character in the string
if (c == userInput) {
++numCount;
}
}

cout << numCount << endl; // Output the count

return 0;
}

The for loop in the code steps through each character in the userStr. Whenever the character matches the userInput, the variable numCount is incremented. This accurately counts the appearances of the specified character.

User Gilgamesz
by
4.9k points