Function that takes a string and character and returns number of occurrences of character in the string

Function that takes a string and character and returns number of occurrences of the character in the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int countChars(const string& s,char c){
int count=0;
for(int i=0;i<s.length();i++){
if(s[i]==c)
count++;
}
}
int main(){
string s;
char c;
cout<<"Enter a string of text\n"
cin>>s;
cout<<"Enter char\n";
cin>>c;
countChars(s,c);
cout<<countChars<<"\n";
return 0;
}


Trying to figure out why it keeps returning 1 no matter what I put in. Any help will be greatly appreciated.
Your compiler might say something like:
warning: no return statement in function returning non-void [-Wreturn-type]
Sorry forgot to include that in my source code. I actually have return count; at the end of the function
Ok, what do you do in main() with the value that the function returns?
int main(){

string s;
char c;
cout<<"Enter a string of test\n";
cin>>s;
cout<<"Enter char\n";
cin>>c;

countChars(s,c);

cout<<countChars<<"\n";


return 0;

}
Thanks for your help.
We can see that code in the OP.

The question is "What are you doing with the value countChars returns?"

The answer is: "You discard it without using it."

Don't ignore the return value in main.
Topic archived. No new replies allowed.