Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
hi!

i want to concatenate a string with an integer that's why i used this code :
C++
++k;
	    char f[50];
		sprintf(f,"%d",k);  
		strcat ( f,"N");

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
Posted
Comments
Status BreakPoint 18-Aug-13 21:15pm    
You can use 'sprintf(f, "%s%d", "N", k);' instead of strcat.
Manel1989 18-Aug-13 21:23pm    
Thank you very much , it works :)
[no name] 18-Aug-13 21:26pm    
Post as a solution.
Manel1989 18-Aug-13 21:27pm    
okkkkkkkkkkay
[no name] 18-Aug-13 21:30pm    
Not you - you asked the question - Status Breakpoint answered it.

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

thank you "Status BreakPoint "
 
Share this answer
 
Comments
Status BreakPoint 18-Aug-13 23:28pm    
You're welcome.
pasztorpisti 19-Aug-13 3:49am    
Let's share this 5.
If you truly have a string (ie. in a variable), then you can simply do:
C++
sprintf(f, "%s%d", string, k);

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:
C++
sprintf(f, "N%d", k);

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.
 
Share this answer
 
Comments
pasztorpisti 19-Aug-13 3:49am    
A 5 for completing the previous answer with the const stuff.
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:

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


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.
 
Share this answer
 
Comments
Richard MacCutchan 7-Jan-15 11:50am    
I suspect OP lost interest almost 18 months ago.
Aescleal 7-Jan-15 15:44pm    
It popped to the top of recent questions, should have checked the date :-(
Richard MacCutchan 8-Jan-15 4:42am    
Usually due to some trawler adding a non-answer, followed by a protector deleting it. Pity really, since your answers are always worth studying.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900