【问题标题】:stick integer to string and char*将整数粘贴到字符串和字符 *
【发布时间】:2010-01-07 10:08:21
【问题描述】:

如何将整数变量添加到字符串和 char* 变量?例如:
int a = 5;
字符串 St1 = "书", St2;
char *Ch1 = "注", Ch2;

St2 = St1 + a --> Book5
Ch2 = Ch1 + a --> Note5

谢谢

【问题讨论】:

  • 这是作业吗?如果是,请添加作业标签。正如 dirkgently 建议的那样,您需要有另一个字符串,然后您可以使用 sprintf 使用 St1 和 i 制作字符串“Book5”。

标签: string integer char add


【解决方案1】:

C++ 的做法是:

std::stringstream temp;
temp << St1 << a;
std::string St2 = temp.str();

你也可以用Ch1做同样的事情:

std::stringstream temp;
temp << Ch1 << a;
char* Ch2 = new char[temp.str().length() + 1];
strcpy(Ch2, temp.str().c_str());

【讨论】:

  • new char[temp.str().length() + 1]; 不是很 C++,你知道 - 它是 GCC 使用的扩展。
  • 出现几个错误,第一个是关于第一行的。
  • @LiraNuna 嗯,这是 GCC 扩展的什么方式?它只是news 一个字符数组。 (我使用的是 VC2005/2008,但代码在 Comeau 中也可以正常工作,无需扩展)
  • @aryan 试试#include &lt;sstream&gt;
【解决方案2】:

例如,对于char*,您需要创建另一个对两者都足够长的变量。您可以“修复”输出字符串的长度,以消除超出字符串末尾的可能性。如果这样做,请注意使其足够大以容纳整数,否则您可能会发现 book+50 和 book+502 都以 book+50(截断)的形式出现。

以下是手动计算所需内存量的方法。这是最有效但容易出错的方法。

int a = 5;
char* ch1 = "Book";
int intVarSize = 11; // assumes 32-bit integer, in decimal, with possible leading -
int newStringLen = strlen(ch1) + intVarSize + 1; // 1 for the null terminator
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
snprintf(ch2, intVarSize, "%s%i", ch1, a);

ch2 现在包含组合文本。

另外,稍微不那么棘手,也更漂亮(但效率较低),您还可以进行 printf 的“试运行”以获得所需的长度:

int a = 5;
char* ch1 = "Book";
// do a trial run of snprintf with max length set to zero - this returns the number of bytes printed, but does not include the one byte null terminator (so add 1)
int newStringLen = 1 + snprintf(0, 0, "%s%i", ch1, a);
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; } 
// do the actual printf with real parameters.
snprintf(ch2, newStringLen, "%s%i", ch1, a);

如果您的平台包含 asprintf,那么这会容易得多,因为 asprintf 会自动为您的新字符串分配正确的内存量。

int a = 5;
char* ch1 = "Book";
char* ch2;
asprintf(ch2, "%s%i", ch1, a);

ch2 现在包含组合文本。

c++ 不那么繁琐,但我会留给其他人来描述。

【讨论】:

  • #include 应该可以解决这个问题,但如果没有,那么您的构建环境有问题,或者您的平台可能不包含 snprintf。这似乎不太可能,因为它是现有的最重要的代码安全工具之一。
【解决方案3】:

您需要创建另一个足够大的字符串,以容纳原始字符串后跟数字(即将与数字的每个数字对应的字符附加到这个新字符串)。

【讨论】:

    【解决方案4】:
    Try this out:
    char *tmp  = new char [ stelen(original) ];
    itoa(integer,intString,10);
    
    output = strcat(tmp,intString);
    
    //use output string 
    
    delete [] tmp;
    

    【讨论】:

    • 这是不安全的——因为 strcat 只是将更多字节写入原始字符串的末尾,这可能会覆盖附近的变量,从而导致您的程序出现故障或崩溃。另外,作者并没有要求修改原始字符串。
    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多