0

I would like to know how to add a string to array of char*

#define FROM    "<[email protected]>"
#define TO      "<[email protected]>"
#define CC      "<[email protected]>"
#define SUBJECT "TESTING SUBJECT"

string testing("USING variables");
const char * c = "Subject: ";

static const char *payload_text[]={
"To: " TO "\n","From: " FROM "\n","Cc: " CC "\n",c "\n",
"\n", /* empty line to divide headers from body, see RFC5322 */
SUBJECT "\n",
"\n",
"Testing the msg.\n",
"Check RFC5322.\n",
NULL
   };

I would like to add either c or the variable testing to the array of payload_test[] or is there other way to create the array paylod_text[] with user insiated variables.

1
  • you are #defining so many things why not #define subject and body too ? Commented Aug 19, 2012 at 12:05

4 Answers 4

1

If you want to add testing then just put it in the parameters as

testing.c_str()

Also one more way is there

string body="Testing the msg.\n";
body+=testing;
body+="Bye ....";

And to put in array use

body.c_str();
Sign up to request clarification or add additional context in comments.

Comments

1

Why not use a dynamically allocated array?

char **email = malloc(sizeof(*email) * 6);
email[0] = "To: " TO "\n";
...
char buf[256];
snprintf(buf, sizeof(buf), "%s \n", c);
email[3] = strdup(buf);
..

Don't forget to free any string created by strdup() after use.

1 Comment

Is this the same as static const char *payload_text[]={"To: " TO "\n","From: " FROM "\n","Cc: " CC "\n",SUBJECT "\n","\n",c "\n","\n","Testing the msg.\n","Check RFC5322.\n",NULL }; char **email = malloc(sizeof(*email) * 6); char buf[256]; snprintf(buf, sizeof(buf), "To: %s \n", toAddress); email[0] = strdup(buf); snprintf(buf, sizeof(buf), "Subject: %s \n", emailSubject); email[1] = strdup(buf); snprintf(buf, sizeof(buf), "Message: %s \n", emailMessages); email[2] = strdup(buf); email[6]=NUL
0

I'd prefer using string for payload_text instead. then you can easily append characters and other strings t it. and latter payload_text.c_str() it if underlying library needs char*

there is boost::format(). You can use it to replace %1%, %2% with your subject and body. like boost::format("SOME STRING %1% AND THEN %2%") % subject % body

Comments

0

To do this natively in C (versus using the C++ STL classes), you can use strcat:

char* buffer = malloc((strlen(c) + strlen(payload_text) + 1) * sizeof(char));
strcpy(buffer, payload_text);
strcat(buffer, c);

This are only valid if you're sure the input is null-terminated and contains no internal nulls. Otherwise use strncpy and strncat.

To do this in C++ using the STL classes:

string result = string(payload_text);
result += testing;

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.