Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a std::basic_string type to an array of char type?

I get the following error when this code is run:

syslog(LOG_ERR | LOG_USER, "%s",errorString);

cannot convert ‘const string {aka const std::basic_string}’ to ‘const char*’ for >argument ‘2’ to ‘void syslog(int, const char*, ...)’ inServer.cpp /PeCounter
line 478 C/C++ Problem

I am daemonizing the program and the errorString value prints just fine when outputted to stdio using cout, but it will not print when using a syslog call.

Any way to get std::basic_string(char) into the form of 'const char'.

like image 950
bentaisan Avatar asked Oct 19 '12 16:10

bentaisan


People also ask

How do I convert a string to a char in C++?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

Can you convert string to char array?

char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.

How do I convert an int to a char array?

One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );

How do you convert this char array?

Using valueOf() Method The valueOf() method is a static method of the String class that is also used to convert char[] array to string. The method parses a char[] array as a parameter. It returns a newly allocated string that represents the same sequence of characters contained in the character array.


2 Answers

The c_str() or data() member function provides a pointer to the first element of an array of char_type which contains your string. It's valid as long as the string object itself remains valid and unchanged (but beware that operations that may cause reallocations may invalidate the pointer -- best not to store it).

like image 166
Kerrek SB Avatar answered Sep 24 '22 15:09

Kerrek SB


I found that std::basic_string has an item access method c_str() which seems to fix the compiling issue.

Here is a site with more information: http://en.cppreference.com/w/cpp/string/basic_string

like image 43
bentaisan Avatar answered Sep 22 '22 15:09

bentaisan