2

I am trying to add data to a pre-existing char array from an int or string. Code is as follows

int num1 = 10; int num2 = 5; string temp = "Client"; char buf[64] = "This is a message for: " + temp + num1 + " " + temp + num 2;

I appear to get conversion data errors here. I am not too sure on how to convert it correctly to the right data type. I need them to be stored into the char array as this array will then be used with sendto() function for UDP sockets and it is just not simply printing it out to the console/debug window

Edit: Language is c++

3
  • 1
    What language is this in? Commented Feb 23, 2014 at 22:38
  • Depends a lot on the language, which you did not specify. Commented Feb 23, 2014 at 22:38
  • My mistake, language is c++. Edited main post to add this in. Commented Feb 23, 2014 at 22:54

1 Answer 1

1

First of all you need to convert integers to strings. This can be done using sprintf(), itoa() or stringstream with operator <<

The second thing is to understand what operator + does.

"This is a message for: " + temp + num1 + " " + temp + num 2;

First will be taken first two arguments "This is a message for: " + temp. First argument is considerd to be a null-terminated string, second argument is an integer. There is no pre-defined operator + for such operation. So now no need to proceed with sum, we already failed compilation.

I can propose two solutions:

int num1 = 10;
int num2 = 5;
char buf[64];
string temp = "Client";
sprintf(buf, "This is a message for: %s%d %s%d", temp.c_str(), num1, temp.c_str(), num2);
// Dangerous, can walk out of allocated memmory on the stack,
// which may not throw an exception in runtime but will mess the memory

And more safe

#include <sstream>
int num1 = 10;
int num2 = 5;
string temp = "Client";
stringstream ss;
ss << "This is a message for: " << temp << num1 << " " << temp << num2;
ss.str().c_str(); // Message is here
Sign up to request clarification or add additional context in comments.

2 Comments

I probably should have added that I need them to be stored into the char array as this array will then be used with sendto() function for UDP and it is just not simply printing it out to the console/debug window
No problems: size_t size = ss.str().length() + 1; char* message = new char[size]; memcpy(message, ss.str().c_str(), size); message[size - 1] = char(0); But this memory needs to be cleared afterwards or there'll be a leak.

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.