Can anybody tell me what is the use of c_str() function in C/C++?. In which case it is necessary to use it?.
Asked
Active
Viewed 1.2k times
4 Answers
6
When you want to use your string with C-functions
string s = "hello";
printf( "your string:%s", s.c_str() );
AndersK
- 35,813
- 6
- 60
- 86
4
It is a C++ thing, not a C one.
A common use of c_str (from std::string) is precisely to convert a C++ std::string to a const char* C string, which is required by many many low level C functions (e.g. Posix system calls like stat, etc).
Basile Starynkevitch
- 223,805
- 18
- 296
- 547
1
Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
There is a good example of its use here: http://www.cplusplus.com/reference/string/string/c_str/
gosr
- 4,593
- 9
- 46
- 82
0
I presume you're asking about string::c_str()? It's a method that returns a C string representation of the string object. You might need a C string representation to call an OS API, for example.
Carl Norum
- 219,201
- 40
- 422
- 469