【问题标题】:Adding data (string or int) to a char array将数据(字符串或整数)添加到 char 数组
【发布时间】:2014-03-25 09:34:09
【问题描述】:

我正在尝试将数据从 int 或 string 添加到预先存在的 char 数组中。代码如下

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

我似乎在这里遇到了转换数据错误。我不太确定如何将其正确转换为正确的数据类型。我需要将它们存储到 char 数组中,因为该数组随后将与 sendto() 函数一起用于 UDP 套接字,而不仅仅是将其打印到控制台/调试窗口

编辑:语言是 c++

【问题讨论】:

  • 这是什么语言的?
  • 很大程度上取决于您没有指定的语言。
  • 我的错,语言是 c++。编辑主要帖子以添加此内容。

标签: c++ arrays string type-conversion


【解决方案1】:

首先,您需要将整数转换为字符串。 这可以使用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

【讨论】:

  • 我可能应该补充一点,我需要将它们存储到 char 数组中,因为该数组随后将与 UDP 的 sendto() 函数一起使用,而不仅仅是将其打印到控制台/调试窗口
  • 没问题:size_t size = ss.str().length() + 1;char* message = new char[size];memcpy(message, ss.str().c_str(), size);message[size - 1] = char(0);但是这块内存需要事后清空不然会泄露。
猜你喜欢
  • 2022-01-10
  • 2021-03-18
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
相关资源
最近更新 更多