How to properly use the strlen function?

I have to write a function that accepts a C-string as an argument and returns the length of the C-string as a result. The function should count the number of characters in the string and return that number. This is the code I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int StringLength(string StrName, int length);
int main()
{
	string bobString;
	int length;
	cout << "Input a string\n";
	cin >> bobString;
		StringLength(bobString, length);
		return 0;
}

int StringLength(string StrName, int length)
{
	length = strlen(StrName);
        cout << "The length of the string is " << length << endl;
	system("PAUSE");
	return length;
}


And this is the error I get:
error C2664: 'strlen' : cannot convert parameter 1 from 'std::string' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I thought the 1st parameter in the function header (StrName) had to be a string, since the string I am inputting in the main (bobString) is a string, right?
Hi, if you are using string class, you should use it's member functions. In this case those 2 might be useful:
http://www.cplusplus.com/reference/string/string/capacity/
http://www.cplusplus.com/reference/string/string/size/

I think that you could also use function: c_str(), like this:

length = strlen(StrName.c_str());
Last edited on
Notice: C-strings are character arrays, you are using C++ strings which (as nieziemski said) have member functions for that
Topic archived. No new replies allowed.