将字符串与整数连接起来 [英] concatenate a string with an integer

查看:160
本文介绍了将字符串与整数连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!



我想用一个整数连接一个字符串,这就是我使用这段代码的原因:

hi!

i want to concatenate a string with an integer that's why i used this code :

++k;
	    char f[50];
		sprintf(f,"%d",k);  
		strcat ( f,"N");



但我得到的是这个(例如: 1N ),我想要的是这样的事情: N1



你能帮帮我吗



谢谢verry muuuuch



晚安


but what i got is this ( for example :1N) and what i want is some thing like this : N1

Could you please help me with this

Thank you verry muuuuch

good night

推荐答案

解决这个问题你可以像@ Status BreakPoint一样使用说:sprintf(f,%s%d,N,k );'而不是strcat。



谢谢你Status BreakPoint
to solve this you can just use like @ Status BreakPoint said :sprintf(f, "%s%d", "N", k);' instead of strcat.

thank you "Status BreakPoint "


如果你真的有一个字符串(即在一个变量中),那么你可以简单地说:

If you truly have a string (ie. in a variable), then you can simply do:
sprintf(f, "%s%d", string, k);



其中'string'是变量,'k'是int值。



如果字符串是一个常量值(例如你的例子中的N),你可以将它简化为:


where 'string' is the variable and 'k' is the int value.

If the string is a constant value (eg. "N" as in your example) you can simplify it to:

sprintf(f, "N%d", k);



其中'k'是int值。



......实际上,上述两个sprintf()实例都是sprintf_s ()如果你为我编写代码。


where 'k' is the int value.

... and really, both of the above instances of sprintf() will really be sprintf_s() if you write code for me.


只是为了记录 - 除非你有充分的理由去摆弄 sprintf 和C ++的C遗产的其他遗物一样,这种字符串摆弄的方法是使用 std :: stringstream



Just for the record - unless you've got a good reason to be fiddling about with sprintf and other relics of C++'s C heritage the way to the do this sort of string fiddling is to use a std::stringstream:

std::string stick_an_N_in_front_of_an_integer( int k )
{
    std::ostringstream formatter;
    formatter << "N" << k;
    return formatter.str();
}





如果你真的必须把所有藏在字符缓冲区中的东西都看看 std :: strstream 。它类似于 std :: stringstream ,但它的所有输出都改为原始字符缓冲区。



If you've really got to have everything tucked into a character buffer have a look at std::strstream instead. It's similar to std::stringstream but does all its output to a raw character buffer instead.


这篇关于将字符串与整数连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆