Reputation: 39
The goal of my assignment is to write a C++ program that takes in two variables, a character value and a string value. The program is then, with the use of a user-defined function called int CountCharacters() the program is supposed to count the number of times that the user inputted character value is in the user inputted string value.
So far I have been able to code what I think at least is a good foundation, but when I run it, I get a crazy big number that also changes each time I run the program.
Below is the program that I have written so far:
Tested Input: n Monday
Expected Output: 1
Received Output: 22091
#include <iostream>
using namespace std;
int CountCharacters(char userChar, string userString) {
int casesFound = 0;
int n = userString.length();
for (int i = 1; i < n; i++) {
if (userString[i] == userChar) {
casesFound = casesFound + 1;
}
}
return casesFound;
}
int main() {
char cVal;
string sVal;
int casesFound;
cin >> cVal;
getline(cin, sVal);
CountCharacters(cVal, sVal);
cout << casesFound << endl;
return 0;
}
Upvotes: 0
Views: 121
Reputation: 59
The reason you got different numbers is that you output casesFound
without assigning a value to it. Reading uninitialized variables makes your program have undefined behavior - so anything could happen. If your function returned 1
it wouldn't have mattered because you do not assign that value to casesFound
. You can assign the value of your function returned to casesfound
like this:
casesFound = CountCharacters(cVal,sVal);
And then proceed to
cout<<casesFound;
Or you could print the returned value directly without assigning it to a variable:
std::cout << CountCharacters(cVal, sVal) << '\n';
Also note that you have bug in your loop. The first index in arrays and strings etc. is 0
in C++, not 1
, so you wouldn't be able to count the M
in Monday
.
Upvotes: 1