11

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

1
  • 1
    Submitting your own answer is perfectly acceptable here. You don't need to include it in your question, even with a later edit. Oct 19, 2012 at 16:11

2 Answers 2

9

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

6

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

4
  • 2
    Only c_str() guarantees a terminator at the end of the string. data() may point to an unterminated copy of the string, which is dangerous for most APIs that are expecting a const char *. Oct 19, 2012 at 16:22
  • 3
    @AdrianMcCarthy: Depends on the version of C++ you are using. In C++11 data() is nul-terminated as well (and guaranteed to be valid even on empty strings). So in C++11 the only difference between c_str() and data() really is the const-ness. Oct 19, 2012 at 18:26
  • @Matthieu M.: You're right--I was looking at the previous version of the spec. Still, there are a lot of people using old libraries, so the distinction might be important. Also c_str() is a little more suggestive of the intent. Oct 19, 2012 at 19:43
  • @AdrianMcCarthy: Yes, the distinction really is important. Both the non nul-terminated and the "undefined" if empty aspects! The C++03 spec left more margin for implementation, but in doing so it made it opened more undefined holes. Oct 20, 2012 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.