0

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?

4
  • Try using char* inCstring; instead of char inCstring[20]{};. Commented Jan 28, 2016 at 2:36
  • 5
    Do you know what c_str does? Commented Jan 28, 2016 at 2:39
  • If you found a solution, you should post it as an answer, not in the question. Commented Jan 28, 2016 at 3:08
  • You can't assign to arrays in C or C++. Commented Jan 28, 2016 at 3:09

2 Answers 2

3

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

4 Comments

Just noticed OP figured out the same answer as "Method B". I do not believe anything is wrong regarding "programming style", only to it not being a 'lvalue =' assignment. Method A is lacking because the new cstring is const.
The problem is that he was trying to assign to an array (char [] type) , not char * .
@M.M That is true. Yet it should be noted that in the sample code, directly swapping char inCstring[20]; to char* inCstring; causes a segmentation fault.
And attempting the lines char* inCstring; inCstring = str.c_str(); produces invalid conversion error by the compiler.
3

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.