writing a program that finds length of a string

Hello there all,
I'm new to the forum here and pretty much new to C++. I'm learning it out of a book right now and I've been working on a program that I can't quite seem to get right. The project is to write a program that finds the length of a given string. I'm not quite sure what I'm doing wrong and I could really use some help. I won't bother posting the error messages because they are unholy long. Here's the code:
//Trying to make a string length function

#include <iostream>

using namespace std;

int len(char *string);

int main() {
char str[] = "Last night I had the strangest dream";
cout<< "The string length is: "<< len(str)<< "\n";

return 0;
}

int len(char *string){
int length;
for (length=0; string[length]; length++)
return length;
}


So. What do the programming geniuses of the interwebs think? Where am I getting my hiccup?
regards,
cuttlefish
There's a missing semicolon that causes len() to always return 0.
It should work with that, but there's a couple things I'd change:
1. You should use an unsigned type for the length.
2. len() should receive a const char *.


By the way, http://www.cplusplus.com/reference/clibrary/cstring/strlen/
why don't you use the string class (http://cplusplus.com/reference/string/string/) and use this to get the size;

std::string str;
str="text";

int length = str.size();

Wow, such wonderfully speedy replies.
Helios, thanks a lot. That fixed it right up. It's hilarious how you can get ten pages of error messages for one missing semi colon. I've also made the changes that you suggested, though I'm not really sure what const does. I've looked it up, but the explanation is a little vague. Why exactly is that better grammar than leaving it out?
Cojones, your link doesn't work so I'm not quite sure what you're telling me to do, thanks anyway.
const char* says to the caller of the function that len() will not modify the contents of the string.

char* does not say that.
http://cplusplus.com/reference/string/string/ it is without the ( ) I didn't think that it will take the () in the link. Try it now. :)
Topic archived. No new replies allowed.