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

How to Combine Strings and Integers in C ?

Linda Hamilton
Release: 2025-01-02 21:43:42
Original
862 people have browsed it

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);
Copy after login

2. Using C 11's to_string()

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

3. Using FastFormat

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

4. Using IOStreams

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

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);
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template