-   Programming (
-   -   Question with c++,string and arrays? (

peacepanda 10-09-2012 05:40 AM

Question with c++,string and arrays?
I want your opinions and also a solution for my underlying problem if possible.

Here is the problem.
I have a structure say

struct Property
char name[100];
char value[100];
I want to execute a couple of looping statements like this

strcpy(user_property[0].value,((const char*)Getvalue1()));

Here Getvalue1() is a memeber function of a class that returns a string value I have to actually run a loop to assign 15 such values.This can be done if I pass array indexes so first I have to store the values value1 etc and (const char*)Getvalue1() in some array but I am not sure how to do this I tried doing the same but I have the following compilation errors

This is the sample code that I have done
PHP Code:

struct Property  user_property[2];
my_Class response;
string sample xmlrMQresponse.GetMQErrorCode();
string sample1 xmlrMQresponse.GetMQStateCode();

char* const list1[] = {"stateCode","errorCode"};
char* const list2[] = {sample1};
size_t len sizeof(list1) / sizeof(list1[0]);
        for (
size_t i 0<leni++) {

The compile error I am getting is

PHP Code:

connot convert std::string to const char in initialization 

at line
PHP Code:

const char* const list2[] = {sample1}; 

Can someone help me with the resolution here?


JohnGraham 10-09-2012 05:50 AM

Use "sample1.c_str()" instead of just "sample1". c_str() returns a pointer to a char buffer representing the underlying string - it's guaranteed not to change so long as you only use const methods on the string (if I remember correctly).

Also, consider abandonning strcpy() and using strncpy(), it's safer (i.e. will save you headaches later on).

dwhitney67 10-09-2012 06:51 AM

@ the OP,

Unless you are developing real-time code, I would also recommend abandoning character arrays for storing strings. Just store them within an STL string.


struct Property
    std::string name;
    std::string value;

Property user_property[2];    // no need to specify struct in declaration

std::string sample  = "mqErrorCode";
std::string sample1 = "mqStateCode";

const std::string list1[] = { "stateCode", "errorCode" };
const std::string list2[] = { sample1 };
const size_t len = sizeof(list1) / sizeof(list1[0]);

for (size_t i = 0; i < len; ++i)
    user_property[i].name  = list1[i];
    user_property[i].value = list2[i];    // BUG HERE!  list2 only has one item, not two.

peacepanda 10-16-2012 04:52 AM

Hi dwhitney67 and dwhitney67 thanks for your responses.That helps.


All times are GMT -5. The time now is 03:56 AM.