简体   繁体   中英

how to add a int to a char[] in c/c++

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

In C++:

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

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

在C ++ 11中:

std::string result = "my text" + std::to_string(i);

(To complement Luchian's answer)

In C:

char myString[128];
int i = 123;
snprintf(myString, sizeof(myString), "My Text %d", i);

假设mystring足够大,在这个例子中就是这样:

sprintf( myString, "my text%d", 123 );

使用C ++中的Qt QString对象:

std::cout << QString("my text %1").arg(123456);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM