amol_Dee_sandwich
amol_Dee_sandwich

Reputation: 65

Using c.str to convert from string to cstring

I am practicing some work with cstring and string. Going from string to cstring using c_str() I get an incompatible data type compile error. For example this is the code that gives said error:

string str = "StackOverFlow";
char inCstring[20]{};
inCstring = str.c_str();

Any ideas?

Upvotes: 0

Views: 2969

Answers (2)

amol_Dee_sandwich
amol_Dee_sandwich

Reputation: 65

So I have figured out two ways to accomplish this.
First, it is important to remember that you can't assign to a whole array, meaning it is necessary to specify the element of the array to assign to. Attempting to assign a string to char array simply will not work for this reason.
That being said, by specifying the element it would be possible to assign a character in a specific element of a char array.
Below are two methods that accomplish a string to cstring(string to char array) "conversion". Please see answer by Vincent for complete code. I have found Method B better since I would like to have max size on my character array.

Method A:

string str = "StackOverFlow";
const char* inCstring;
inCstring = str.c_str();

Method B:

string str = "StackOverFlow";
char inCstring[20]{};

Then use strcpy

strcpy(inCstring, str.c_str());

Upvotes: 3

Vicente Cunha
Vicente Cunha

Reputation: 204

The problem is that str.c_str() returns a const char*, and you are trying to pass it to a char*. Use strcpy to get your expected result:

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
    string str = "StackOverFlow";
    char inCstring[20];

    strcpy(inCstring, str.c_str());

    cout << "str: " << str << endl;
    cout << "inCstring: " << inCstring << endl;

    return 0;
}

Upvotes: 3

Related Questions