Hi guys,

I've been trying for over 3 hours just to know how to compare a char to a letter in a string. This is sure confusing, consider that I am a mechanical eng. student >.< Lets get straight to the point

Problem 1: passing string and char to a function, and display it

#include <iostream>
#include <string>

using namespace std;

void CountLetter(string a, char b)
{

	cout << a << "\n";
	cout << b << "\n";


}

int main()
{
	CountLetter("tttyuttt", 't');

	return 0;
}

Problem 2: after I can pass the char and string to that function, I can use the following code to figure out how many times t is repeated in the first argument.

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str1 ("Test stringeeeeeeeeeeee");
	char str2 ('e');

	int i;
	int count=0;

	for (i = 0 ; i < str1.length() ; i++)
	{
		if (str1[i]==str2)
			count++;
	}
	cout << "total: " << count;
	cin >> i;
	return 0;

}

So I have two questions:

1. How do you guys pass char and string to a function (the correct way)?

2. Is my code for counting a letter in a string the best way? Is there any better/more efficient way to do it ?

Thank you for your help !

1. How do you guys pass char and string to a function (the correct way)?

There's not really anything wrong with how you did it.

2. Is my code for counting a letter in a string the best way?

I would only have minor nitpicks. The algorithm is sound.

@Narue: ... it wasnt working before ... I've been googling and they suggested string& and char * something too ... Thanks a lot for your resposne anyway, this is the main reason why i can never do IT. >.<

1 more question: when i assign a variable of type string str1 to a, and variable of type char to str2, how do u do that ? Just wondering.

#include <iostream>
#include <string>

using namespace std;

void CountLetter(string a, char b)
{
	string str1 = a;
	char str2[1] = b;

	cout << str1 << "\n";
	cout << str2 << "\n";


}

int main()
{
	int a;
	CountLetter("tttyuttt", 't');
	cin >> a;
	return 0;
}

To return a value from the function and assign it to the integer a (as in your code):
1) Make the function an int instead of void
2) Set an integer variable val to some value in the function
3) return val; at the end of the function
4) Set a to the function in main() , like so: a = CountLetter("tttyuttt", 't'); I like the way you are writing small snippets of code to understand the program parts. Most people get so lost because they don't to this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.