Calling/Passing String Function Into Main

Beginner C++ student here, first ever programming class. I am trying to put together the program below. It's supposed to ask the user for an input string, then a specific char to look for within that string, and output how many times it appears.

For example:

input: 1+2+3

look for: '+'

It appears 2 times.

I am learning string functions in the format shown in the code, where I call a function. However, I am still learning how to call the function in the main. So, I am wondering if someone kindly advise as to how I can tell the main to use the function howMany and output the 'counter' value from the loop.

Thank you very much!

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

bool die(const string & msg);

unsigned howMany(char c, const string & s, unsigned counter);

int main() {

    char c;
    string s;
    unsigned counter = 0;

    cout << "Enter a string: " << endl;
    getline(cin, s);
    cout << "Enter char: " << endl;
    cin >> c;

    cout << "The char chosen appears " << howMany(counter) << endl; //<---- **HELP WITH COUT HERE**

}

unsigned howMany(char c, const string & s, unsigned counter) {

    //unsigned counter;

    for (unsigned i = 0; i < s.length(); i++){
        if (s[i] == c){
            counter++;

        }

        return counter;
    }


}

bool die(const string & msg){
    cout << "Fatal error: " << msg << endl;
    exit(EXIT_FAILURE);
}

Answers


int count = howMany(c, s, 0);

but its odd that you pass in a counter (thats why I put 0), you just want it to return a counter. Looks like you have that to start with but changed you mind (the commented out counter in the homMany function). I would have

unsigned howMany(char c, const string & s) {

    unsigned counter = 0;

    for (unsigned i = 0; i < s.length(); i++){
        if (s[i] == c){
            counter++;

        }

        return counter;
    }

}


Found a solution. Final working program.

 #include <fstream>
 #include <iostream>
 #include <string>
 #include <cstdlib>
 #include <algorithm>

 using namespace std;

 bool die(const string & msg);

 unsigned howMany(char c, string & s);

 int main() {

     char c;
     string s;

     cout << "Enter a string: ";
     getline(cin, s);
     cout << "Enter char: ";
     cin >> c;

     cout << "The char chosen appears " << howMany(c, s) << endl;


 }

 unsigned howMany(char c, string & s) {

     transform(s.begin(), s.end(), s.begin(), ::tolower);

     size_t n = count(s.begin(), s.end(), c);

     return n;

 }

 bool die(const string & msg){
     cout << "Fatal error: " << msg << endl;
     exit(EXIT_FAILURE);
 }

Need Your Help

Using eval in defing Python class data attributs

python class eval

I wonder if it possible to use eval to creates class data attributes. Something like following code: