So I picked up this example from this website itself and it helped me be able to copy a string into a char array like I wanted to. However, I do not understand the last line.
1 2 3 4 5 6
string name;
name = "Vane";
char ch[30];
std::size_t length = name.copy(ch,name.length(),0);
cout << length << endl ; //this prints out 4
ch[length]= '\0';
Can someone please explain to a noob how does: ch[length]= '\0'; work? What exactly is this line doing, because to me it appears that it is just deleting my entire array. Or is it working in conjunction with a previous line that I perhaps did not fully understand?
Since my ch[30] is too many spaces to fit only 4 characters, that last line seems to clean it up for me but I want to understand the logic behind that. If you will notice, my string was just four characters long, but my array was had 30 slots.
In the end my array has as many slots as there are characters in my string.
C-style strings, which is whart these are called, are terminated with a null character which is '\0'. The line of code only refers to the last character not all of the array.
The terminator specifies the end of the string. Like a transparent full stop.
I believe when the copy assignment is called it would copy until it hits the '\0' character. So as it copied, it counted the characters up to the end character. And since arrays start at 0, the char[length] = '\0' would be setting the char array to a proper C-string for in case of other uses for the string.
There is only one null terminator produced by char[length] = '\0'.
Everything after that is junk, unused but in an allocated 30 characters memory.
You can put nulls in the other unused parts of the array if you want but char[length] is not the way to do it. You'll need a loop because char[length] only refers to one spot.
Try it, and print out ch[length + 1] . See what happens.
@kemort
If putting '\0' in the location char[length] not the way to do it, then why does the sample produced by the cplusplus reference for string::copy use it and not use a 'proper way'?
kemort did not say char[length]='\0' was wrong, just that it will not fill the rest of the character array with null characters (i.e., "with regards to putting null characters it the rest of the string, char[length]='\0' is not the way to do it" is what was being said).
But when it comes to an array of characters that is going to be acted as a C-string, you use the null character to determine the end of the string. The rest of the array you wouldn't honestly care about. This is why when you cout the C-string it doesn't spit out the random info that was in the array after the null character.