怎么把一个数字加在一个字符串后面得到一个新串?

ding525 2008-10-10 05:29:20
c++中,怎么把一个数字加在一个字符串后面得到一个新串?谢谢
...全文
1373 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
alafeizai 2008-10-10
  • 打赏
  • 举报
回复
#include <iostream>
#inlcude <string>
#inlcude <sstream>

string to_string(int n)
{
ostringstream ss;
ss << n;
return ss.str();
}

int main()
{
int i = 10;
string s = "test";

s = s + to_string(i);

cout << s << endl;
system("pause");

re 0;
}
elegant87 2008-10-10
  • 打赏
  • 举报
回复

//可以直接用string类库
#include<iostream>
#include<string>
using namespace std;

int main()
{
string str="afagasg";
str+="123";
cout<<str<<endl;
return 0;
}
baihe_591 2008-10-10
  • 打赏
  • 举报
回复
#include <string>

string s1="abc";
string s2="4";
string s3=s1+s2;
aaajj 2008-10-10
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 zclever 的回复:]
char str[]="HelloWorld";
int value=100;
char buff[10];
itoa(value,buff,10);//转化成字符串
strcat(str,buf);//字符串拼接函数
cout < <str;//输出HelloWorld100
当然要包含头文件string
[/Quote]
zhkefa 2008-10-10
  • 打赏
  • 举报
回复
C++ 的字符串string有重载+操作符的,把数字直接转为string加到原来的string即可,

C风格的字符串,可以用strcat()函数,,
chlaws 2008-10-10
  • 打赏
  • 举报
回复
是int 则转成string 然后直接加就行了
就呆在云上 2008-10-10
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


char * mycpy(char *p, int a);
int count(int a);
int main(int argc, char* argv[])
{
int a = 12345678;
char *p = "9999";
char *pp = mycpy(p, a);
puts(pp);
free(pp);
return 0;
}

char* mycpy(char *p, int a) {
if (!p)
{
printf("Oh, no!\n");
return NULL;
}
int count_of_a = count(a);
count_of_a += strlen(p) + 1;
char *pp = (char *)malloc(count_of_a);
strcpy(pp, p);
sprintf(pp+strlen(p), "%d", a);
return pp;
}

int count(int a) {
if (a == 0)
{
return 1;
}
else {
a /= 10;
if (a == 0)
{
return 1;
}
else
return count(a)+1;
}
}
zclever 2008-10-10
  • 打赏
  • 举报
回复
char str[]="HelloWorld";
int value=100;
char buff[10];
itoa(value,buff,10);//转化成字符串
strcat(str,buf);//字符串拼接函数
cout<<str;//输出HelloWorld100
当然要包含头文件string
Dan_M 2008-10-10
  • 打赏
  • 举报
回复
STRING STR3,STR1,STR2;
STR1 = "DFHFGHGFHDF";
STR2 = "7";
STR3 = STR1 + STR2;
OenAuth.Core 2008-10-10
  • 打赏
  • 举报
回复
ysuliu 2008-10-10
  • 打赏
  • 举报
回复
strcat()
连接两个字符串

64,644

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧