Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: String Functions without <cstring>

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>;

like image 217
Mohamed Ahmed Nabil Avatar asked Aug 05 '12 18:08

Mohamed Ahmed Nabil


People also ask

Should I use Cstring or string?

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.

Does Cstring include string?

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 .

Is string H same as Cstring?

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).


2 Answers

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.

like image 54
Vlad Avatar answered Nov 15 '22 03:11

Vlad


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
like image 33
log0 Avatar answered Nov 15 '22 03:11

log0