c++: <cstring> vs. <string>

Hello programmers. I'm a little confused of cstring and string in c++
Can I use both #include<cstring> and #include<string> in the same cpp file?

I know the major difference is that cstring is null terminated and c++string is not.
If a cpp file has both #include<cstring> and #include<string> , how to distinguish between a cstring array and a string array would just be the datatype?

If there is a char array as below, is it always a cstring?
 
  char arr[]="abc"; 

will the array size be always 4 as cstring? or can it be 3 as just a regular array?
<cstring> defines functions which work on char array strings, like strcmp, strstr, strchr and such. <string> defines the std::string class and functions like std::getline. Including <cstring> or not, all string literals in C and C++ are null-terminated, so answering your question, char arr[]="abc"; is 4 bytes long. (considering only ASCII characters. UTF-8 Unicode characters are up to 8 bytes long, so a 3 character unicode string could be up to 25 bytes long)
Can I use both #include<cstring> and #include<string> in the same cpp file?
Yes.

A C string is not a data type, it's a data format. The header <cstring> contains convenience functions that manipulate C strings.
In your example above, arr is not a C string. It's array that contains a C string. It could be overwritten to contain something else. For example:
1
2
3
char arr[] = "abc";
for (int i = 0; i < 4; i++)
    arr[i] = i + 1;
Now arr no longer contains a C string, because a C string is supposed to mark its end with a null character, but arr ends before any null character can be found. If you pass arr to any C string manipulation function, such as strlen(), you'll cause undefined behavior, because the program will continue reading past the end of arr.

On the other hand, <string> does define several data types, such as std::string, std::wstring, etc.

As for your other question, yes, an array declared as char arr[] = "abc"; is guaranteed to be as long as the specified string, plus 1 more element to hold the null character. It's equivalent to
 
char arr[] = { 'a', 'b', 'c', 0 };
Last edited on
most of the <cxxxxx> headers are from C, and have a c++ replacement.
Some of them make no sense, like <cmath> (apparently math went out of style?) but you have things like cmemory (direct memory manipulation, generally very fast but troublesome with objects and requires skill to avoid errors), cstdio (printf, etc), cstdlib, and quite a few others. Most, but not all, of the headers that end in .h have a new namespace friendly c++ Cxxxxxx version, and again, most of those have an object oriented/stl/etc c++ replacement anyway.

also, there is an old string class (from windows, maybe) called Cstring, which is something else entirely.

Thank you programmers! all make so much sense! :)
Topic archived. No new replies allowed.