string length function.

Im having trouble putting together a string length function that counts the number of characters in the string. I know im suppose to use the strlen but thats about it. Any constructive info would be greatly appreciated.

this is all i have right now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// function that returns an integer and accepts a ptr to a C-string as an argument.
#include <iostream>
#include <cstring>   // must have for strlen
#include <string>
using namespace std;

//********************************************
// function stringLength
// this function counts the number
// of characters in the string and
// returns that number.
//********************************************
int stringLength(char *str)




int main()
{
	string userInput;		// user 

	// get a string from the user.
	cout << "Enter a string.\n";
	getline(cin, userInput);


	// call function stringLength
	stringLength(userInput);
	return 0;
}







Last edited on
Makes no sense whatsoever, but:

int stringLength(char *str) {return strlen(str);}
or
int stringLength(const string& str) {return str.length();}
"Makes no sense whatsoever" Could you elaborate?
But put the same thing that I have minus the return. I don't understand how to put in a counter for the number of characters the user enters using strlen.
I don't understand how to put in a counter for the number of characters the user enters using strlen
See:
int stringLength(char *str) {return strlen(str);}

"Makes no sense whatsoever" Could you elaborate?

It makes no sense to have a separate function "stringLength", when you could just call userInput.length() directly.
Last edited on
I started programming 9wks ago so right now I do whatever my instructor and Tony Gaddis tell me to.
But could someone address the underlined portion of my second post? Any constructive feedback would be appreciated.

All ive seen in my textbook are loops for counting characters instead of{ return strlen(str);} which does seem alot simpler ill give that a shot.
I keep getting a C2664 error. I googled it and read up on it but still cant figure out what im doing wrong.
Last edited on
problem solved.
Topic archived. No new replies allowed.