【问题标题】:Append an int to char*将一个 int 附加到 char*
【发布时间】:2010-09-25 17:13:01
【问题描述】:

如何在 c++ 中将整数附加到 char*

【问题讨论】:

    标签: c++ integer char append


    【解决方案1】:

    首先使用sprintf()将int转换为char*

    char integer_string[32];
    int integer = 1234;
    
    sprintf(integer_string, "%d", integer);
    

    然后要将其附加到您的其他 char*,请使用 strcat():

    char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string
    
    strcat(other_string, integer_string); // other_string now contains "Integer: 1234"
    

    【讨论】:

    • 如果 sizeof(int) > 4,你手上有一个缓冲区溢出漏洞。
    • @Tom:我不习惯使用 int 类型(我总是使用 u8、u16、u32 等类型)所以我没有想到……我会改变那么字符串的大小。
    • 为了安全起见,应该使用 snprintf 和 strncat。
    • 为什么不通过 sprintf 来做这一切呢? snprintf(other_string, 64, "Interger: %d", integer);
    • 您可能希望使用类似 +sizeof(int)*3+1 (3 = ceil(8*log10(2) ), 1 代表'-')。这应该始终有效(在 128 位整数等情况下也是如此),并且还避免了不必要的大分配(可能不是问题)。
    【解决方案2】:

    你也可以使用字符串流。

    char *theString = "Some string";
    int theInt = 5;
    stringstream ss;
    ss << theString << theInt;
    

    然后可以使用ss.str();访问字符串

    【讨论】:

      【解决方案3】:

      类似:

      width = floor(log10(num))+1;
      result = malloc(strlen(str)+len));
      sprintf(result, "%s%*d", str, width, num);
      

      您可以通过使用系统上整数的最大长度来简化 len。

      edit 哎呀 - 没有看到“++”。不过,它是一种替代方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 2012-07-05
        • 2013-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多