\0 and string - C++

Mar 22, 2009 at 2:04pm
1
2
3
4
string msg = "33.44.55.66";
cout<<msg<<endl;
msg.insert(6, "\0");
cout<<msg<<endl;


The output of both shows as 33.44.55.66! The second one should break at 6, right?!
Mar 22, 2009 at 2:37pm
msg.insert(6, "\0");
inserts all the characters before a '\0', so it won't insert anything

Anyway a string has a length, so it isn't terminated by a '\0'
Mar 22, 2009 at 2:46pm
If i do msg.insert(6, "ff");

i get a result off 33.44.ff55.66!

>>Anyway a string has a length, so it isn't terminated by a '\0'

so strings are not terminated by \0 as in char *! ok...this null char thing confuses me
Mar 22, 2009 at 2:57pm
In c++ you can forget '\0' if you use string class, you just don't need to worry about it.

it's normal to have 33.44.ff55.66! result, insert is a function which appends something in the desired position but don't replace any value in that position, just makes an insertion.

Help:
http://www.cplusplus.com/reference/string/string/insert.html
Mar 23, 2009 at 3:59am
Null characters were needed in C because if you did something like
char myText[] = "HELLO";
myText would really be a pointer to somewhere in memory, let's say for example, it's at memory location 100 (which it probably wouldn't be but that's a nice round number), the memory might really look like
100: HELLO\0askdj7y3hcdm,chy3nc73hjkcz78zxcojczxkj
Without that \0 (null character) there, C wouldn't know whether the string was H, HELLO, HELLOaskdj or anything else.

However, in C++ "strings" are no longer null-terminated because the string object can store not only what characters make up the string (as C did), but how long it should be, so a C++ string can just say "HELLO" is 5 characters, so start at the pointer and read 5 characters.
Topic archived. No new replies allowed.