将整数粘贴到字符串和字符*

时间:2010-01-07 10:08:22

标签: string integer char add

如何将整数变量添加到字符串和char *变量?例如:
int a = 5;
string St1 =“Book”,St2;
char * Ch1 =“Note”,Ch2;

St2 = St1 + a - > Book5两个
Ch2 = Ch1 + a - >注5

由于

4 个答案:

答案 0 :(得分:2)

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());

答案 1 :(得分:1)

对于char*,您需要创建另一个足够长的变量,例如。您可以“修复”输出字符串的长度,以消除超出字符串结尾的可能性。如果你这样做,要小心使它足够大以容纳整数,否则你可能会发现书+ 50和书+ 502都是书+ 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 ++不那么繁琐,但我会将其留给其他人来描述。

答案 2 :(得分:0)

您需要创建另一个足够大的字符串来保存原始字符串,后跟数字(即将与该数字的每个数字对应的字符附加到此新字符串)。

答案 3 :(得分:-1)

Try this out:
char *tmp  = new char [ stelen(original) ];
itoa(integer,intString,10);

output = strcat(tmp,intString);

//use output string 

delete [] tmp;