1

I need to convert char array of C into string c++ but the char array is an element of struct.

Code:

This is my Structure in C

typedef struct myStruct
{
    char name[50];
    char abc[50];
    ESL_BOOL status;
}MyStruct;

and I want to access name[50] in c++ but for that I have to convert it into string. I have tried strcpy and memcpy. I am using ESL_BOOL status; and it is working but confused with name[50].

0

2 Answers 2

3

The first thing you should change in the class name in your struct because that will likely cause problems because it is a keyword in C++.

Then for converting a C string into a C++ one, you can simply use the std::string constructor that accepts C-style strings.

std::string myCppString(MyStruct.name);
Sign up to request clarification or add additional context in comments.

2 Comments

ThanksSir I need to assign this char array to string element of
I don't understand what you want to do exactly. Do you mean like you want to copy a char[50] into another?
0
typedef struct myStruct {
    char name[50];
    char mclass[50];
    ESL_BOOL status;
} MyStruct;

class is a reserved keyword of the C++ language. If you try to use it, tokenizer will take it as a keyword and cause problems later in the parsing phase, as an identifier will be expected.

It was once considered a good practice to precede all of the struct´s members with m or m_ to avoid such collisions.

To your problem: just the default "from C string" string (const char* s) constructor should be enough.

MyStruct obj;
std::string objsName(obj.name);
std::string objsClass(obj.mclass);

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.