Skip to main content
gamedev.net
🔒 Locked

Char length

Started by hungryhippo5000 Feb 20, 2005 at 12:36 PM 5 replies 900+ views
Original Post
hungryhippo5000
hungryhippo5000
How would you get the length of a "char *" in C++? For example, how would you know what the length of the following char is? char* string; cin >> string;
grekster
grekster
strlen(string); I think works. You could also just loop through the string count the number of characters before the null terminator (assuming its a null terminated string).
Quote: Original post by BosskIn Soviet Russia, you STFU WITH THOSE LAME JOKES!
Zahlman
Zahlman
How long is a piece of string, anyway?

The pointer has no length in and of itself; the "string length" you're talking about is defined by convention ("read through memory until the first \0 character, and that's the end"). Of course, there is a legacy function call left over from C that looks after that for you (strlen()), but why are you messing around with this kind of stuff?
std::string foo; // an object, not just a pointercin >> foo; // one wordgetline(cin, foo); // one linefoo.length(); // length of the string, which is a real "string"foo += "bar"; // much more readable than the C equivalent, and probably faster too// (the string implementation will cache the string length, while raw C-style// "strings" have no such concept; the runtime must look up the null terminator// every time)
Trap
Trap
Quote:
Original post by hungryhippo5000
char* string;

cin >> string;

Access violation, you would need to allocate a buffer first. But then you don't know how big it has to be.

One should never use cin >> charpointer. It's a sure buffer overflow bug.
bkt
bkt
If you're using std::string then string.length() would work. But if you're using char* you can simply use the age old strlen(char*); which I think resides in #include (not sure though)
-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]
ToohrVyk
ToohrVyk
Or #include , but you'd need to allocate enough memory for the character array before reading it.

ToohrVyk, head of the CRCSCCA (committee for renaming C strings to C character arrays)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.