2

i have a code like this:

int i = 123;
char myString[100];
strcpy(myString, "my text");

and how i want to add the 123 after "my text". how to do this in c/c++?

at the end myString sould be my test123

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

5 Answers5

8

In C++:

std::stringstream ss;
ss << "my text" << i;
std::string resultingString = ss.str();

There's no such thing as C/C++.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
7

In C++11:

std::string result = "my text" + std::to_string(i);
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
6

(To complement Luchian's answer)

In C:

char myString[128];
int i = 123;
snprintf(myString, sizeof(myString), "My Text %d", i);
  • 2
    Note: this only works if `myString` is an array. If it's a pointer instead, you must keep track of the length of the pointed-to buffer and pass that in as the second argument of `snprintf`, since `sizeof(pointer)` is not what you want (it's typically 4 or 8 bytes). – Adam Rosenfield Sep 27 '12 at 20:02
  • Yeah, I was just adding clarification in case anyone came by and decided to copy+paste the code without fully understanding it. – Adam Rosenfield Sep 27 '12 at 20:57
  • @AdamRosenfield valid reason, absolutely. (NO ONE should copy-paste code without understanding it though, right?) –  Sep 27 '12 at 21:03
4

Assuming mystring is large enough, which it is in this example:

sprintf( myString, "my text%d", 123 );
Mark Stevens
  • 2,366
  • 14
  • 9
  • 1
    Sorry, man, but -1 for not using snprintf(). You should really be secure. –  Sep 27 '12 at 19:56
0

With the Qt QString object in C++:

std::cout << QString("my text %1").arg(123456);
fonZ
  • 2,428
  • 4
  • 21
  • 40