0

I need to pass string into socket send() function which accepts char * only. So here I am trying to convert it:

void myFunc(std::string str)  //Taking string here const is good idea? I saw it on some examples on web
{
    char *buf = str.c_str;    //taking buf const is good idea?
    std::cout << str;
}

int main()
{
    const std::string str = "hello world";
    myFunc(str);
    return 0;
}

Gives error:

test.cpp:6:18: error: cannot convert ‘std::basic_string<_CharT, _Traits, _Alloc>::c_str<char, std::char_traits<char>, std::allocator<char> >’ from type ‘const char* (std::basic_string<char>::)()const’ to type ‘char*’
Catty
  • 456
  • 2
  • 7
  • 17

3 Answers3

8

First off, c_str() is a function so you need to call it.

Second, it returns a const char* not a char*.

All in all:

const char* buf = str.c_str();
syam
  • 14,701
  • 3
  • 41
  • 65
  • syam: Why it need to be `const`? it works without it also! – Catty Sep 06 '13 at 18:03
  • 2
    @Catty There was a time when `char* buf = str.c_str()` was accepted as an exception to the usual const-correctness rules, but nowadays this is not valid C++ any more. If your compiler accepts it, it just means it doesn't respect the latest standard. This shouldn't stop you from trying to write correct code, though. – syam Sep 06 '13 at 18:20
1

Try:

void myFunc(std::string str)
{
    const char *buf = str.c_str();
    std::cout << str;
}
Diego Giagio
  • 1,027
  • 7
  • 7
  • Is this correct way to proceed? I dont know, I just wanna know whether it can create any issue later or not – Catty Sep 06 '13 at 18:05
  • If your send() routine accepts a const char* (and it probably does if we're talking about sockets), this is the correct way to proceed. On other hand, if you are sending binary data I would recommend using std::vector instead of std::string. – Diego Giagio Sep 06 '13 at 18:20
  • ok, I am sending string and int value. what is benifit of using vector ? – Catty Sep 07 '13 at 03:51
  • @Catty if you are sending an int value as text, you can use std::string and later call str.c_str(). If you are sending an int value as binary data, you need to encode it (considering endianess) and use a buffer to hold your encoded data. In this case, std::vector is a good choice. – Diego Giagio Sep 07 '13 at 13:20
1

First of all, Call c_str() has a function. After it, c_str() return a const char*, you need to copy it if you want to have a char* using std::strcpy() : http://en.cppreference.com/w/cpp/string/byte/strcpy

Hulor
  • 219
  • 1
  • 5