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*’
1
  • 1
    c_str() ..................... Commented Sep 6, 2013 at 17:51

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

syam: Why it need to be const? it works without it also!
@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.
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

Comments

1

Try:

void myFunc(std::string str)
{
    const char *buf = str.c_str();
    std::cout << str;
}

4 Comments

Is this correct way to proceed? I dont know, I just wanna know whether it can create any issue later or not
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<char> instead of std::string.
ok, I am sending string and int value. what is benifit of using vector <char>?
@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<char> is a good choice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.