Friday, July 31, 2009

How do you obtain the length of a character string in c++?

I'm trying to determine the length of a character string in C++:





char str[ ] = "Hello, world!";


int lengthOfString;


lengthofString = str.length();





doesn't work -- my compiler says that the left side of ".length" requires a class/struct/union type.





What's the correct way to determine the length of a character string in C++?

How do you obtain the length of a character string in c++?
Hi,





Ok. There are two ways of doing what you're doing. First is the one that uses simple character strings.





%26lt;Modified Code -- Start%26gt;


#include %26lt;string.h%26gt; // do this in the start of the file





char str[] = "Hello, world!";


int lengthOfString;


lengthOfString = strlen(str); // this function will return string length of any null-terminated character array


%26lt;Modified Code -- End %26gt;





Second case you've been informed of in previous answers, and they're accurate, so noo need to pass on redundant info :)





Hope this helps. Plus, you need to get a good book on C/C++.
Reply:You are REALLY confused. you are mixing c strings with c++. if you are using a c string(an array of characters), then you need to do things the C way not the c++ way..





your code should be:





#include %26lt;string%26gt;





int main(int argc, char** argv)


{


std::string str="Hello, world!";


int lengthOfString=str.length();


};





the char type just allocates one byte for each element in the array. It is not a class and it does not have any methods. If you need any c++ help(and i assume you do),feel very free to contact me at(iammisc@gmail.com).
Reply:wrong string class


there are C string and C++ string and you're trying to use a C++ string function when you are using a C string.





=======


string str = "Hello, world!";


int lengthOfString;


lengthOfString = str.length();

nil

No comments:

Post a Comment