2014-02-23 46 views
1

我想从int或字符串中将数据添加到预先存在的字符数组中。代码如下将数据(字符串或整数)添加到字符数组中

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

我似乎在这里得到的转换数据错误。我不太确定如何正确地将其转换为正确的数据类型。我需要它们存储到字符数组作为此数组然后用sendto()功能UDP套接字使用,它只是不是简单地打印出来到控制台/调试窗口

编辑:语言是C++

+1

什么语言是这个吗? –

+0

取决于您未指定的语言。 –

+0

我的错误是语言是C++。编辑的主帖添加此。 –

回答

0

首先你需要将整数转换为字符串。 这可以使用sprintf()itoa()stringstream与运营商<<

的第二件事是要了解+做什么操作来完成。

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

首先将采取前两个参数"This is a message for: " + temp。第一个参数被认为是一个以空字符结尾的字符串,第二个参数是一个整数。这种操作没有预定义的操作符+。所以现在不需要进行总结,我们已经无法编译。

我可以提出两个解决方案:

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 

而且更安全

#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 
+0

我可能应该补充说我需要将它们存储到char数组中,因为此数组将随后用于UDP的sendto()函数,并且不仅仅是将其打印出来到控制台/调试窗口 –

+0

没问题: 'size_t size = ss.str().length()+ 1;' 'char * message = new char [size];' 'memcpy(message,ss.str ().c_str(),size);' 'message [size-1] = char(0);' 但是这个内存需要被清除,否则会出现泄漏。 – teivaz