Home >Backend Development >C++ >How to Combine Strings and Integers in C ?

How to Combine Strings and Integers in C ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-02 21:43:42880browse

How to Combine Strings and Integers in C  ?

How to concatenate a String and an Integer in C

Concatenating a string and an integer in C can be done in several ways. Here are a few common methods:

1. Using Boost's lexical_cast

std::string name = "John";
int age = 21;
std::string result = name + boost::lexical_cast<std::string>(age);

2. Using C 11's to_string()

std::string name = "John";
int age = 21;
std::string result = name + std::to_string(age);

3. Using FastFormat

std::string name = "John";
int age = 21;
std::string result;
fastformat::fmt(result, "{0}{1}", name, age);

4. Using IOStreams

std::string name = "John";
int age = 21;
std::stringstream sstm;
sstm << name << age;
std::string result = sstm.str();

5. Using itoa()

std::string name = "John";
int age = 21;
char numstr[21]; // enough to hold all numbers up to 64-bits
std::string result = name + itoa(age, numstr, 10);

6. Using sprintf()

std::string name = "John";
int age = 21;
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
std::string result = name + numstr;

The above is the detailed content of How to Combine Strings and Integers in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn