调用/传递字符串函数到Main

时间:2015-12-03 23:49:48

标签: string loops

初学C ++学生,这是第一个编程课。我想把下面的程序放在一起。它应该向用户询问输入字符串,然后在该字符串中查找要查找的特定字符,并输出它出现的次数。

例如:

输入:1 + 2 + 3

寻找:'+'

出现2次。

我正在以代码中显示的格式学习字符串函数,我在其中调用函数。但是,我还在学习如何在main中调用该函数。所以,我想知道是否有人建议我如何告诉主要使用函数howMany并从循环中输出'counter'值。

非常感谢!

#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);
}

2 个答案:

答案 0 :(得分:1)

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

但奇怪的是你传入一个计数器(这就是为什么我把0),你只是想让它返回一个计数器。看起来你有这个开始,但改变了你的想法(homMany函数中注释掉的计数器)。我会

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;
    }

}

答案 1 :(得分:0)

找到解决方案。最终工作计划。

 #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);
 }