I started learning strings and string functions (from a book) , I learned functions like strcpy
and strcat
and strncat
..etc
So I started to practice using them in simple programs to get a sense of what they do.
Then I was surprised later that in the book it tells me that i have to use #include <cstring>
in order to use all these string functions.
I have tried using string functions more than once without including <cstring>
so why?
The only header file i included was <iostream>
and yet i was able to use string functions.
Please someone explain to me why the string functions worked without <cstring>
and do I need to include it to use string functions, and if no what are the uses of <cstring>
;
Use string. cstring is so 1970's. string is a modern way to represent strings in c++. you'll need to learn cstring because you will run into code that uses it.
CString accepts NULL-terminated C-style strings. CString tracks the string length for faster performance, but it also retains the NULL character in the stored character data to support conversion to LPCWSTR .
The file string. h is used in C programs to get access to a variety of functions for manipulating these arrays of characters. The file cstring is used in C++ programs to get access to these same functions (following the usual convention of stdheaders C++ standard header names).
First of all, you absolutely need to consider switching to std::string
. Manual memory allocation, while being an interesting and sometimes challenging task, should not be a part of your everyday job.
Having said that, probably the <cstring>
was #included by some other header you are using in your project. However it's better not to depend on the other headers including <cstring>
(no one guarantees that they will do always and for every compiler), and include it where appropriate.
You don't need to include <cstring>
because it is included by iostream
.
However note that the function you are talking about (strcpy
, strcat
, strncat
) are C function taking char *
and have their C++ equivalents working with the more convenient std::string
.
strcpy
: std::string::operator=
std::string str2;
std::string str1 = str2; // copy str2 in str1
strcat
: std::string::operator+=
str1 += str2; // concat str2 to str1
strncat
:
str1 += str2.substr(0,n); // concat the first n characters of str2 to str1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With