Heim >Backend-Entwicklung >C++ >Wie kann ich einen std::string und eine Ganzzahl in C verketten?

Wie kann ich einen std::string und eine Ganzzahl in C verketten?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 01:43:14622Durchsuche

How Can I Concatenate a std::string and an Integer in C  ?

Das Verketten eines std::string und eines int

Das Kombinieren eines std::string und eines int zu einem einzelnen String kann ein sein einfache Aufgabe. Hier sind mehrere Ansätze, um dies zu erreichen:

1. Boost verwenden

#include <boost/lexical_cast.hpp>

std::string name = "John";
int age = 21;

std::string result = name + boost::lexical_cast<std::string>(age);

2. Verwendung von C 11

std::string name = "John";
int age = 21;

std::string result = name + std::to_string(age);

3. Verwendung von FastFormat

#include <fastformat/format.hpp>

std::string name = "John";
int age = 21;

std::string result;
fastformat::fmt(result, "{0}{1}", name, age); // FastFormat.Format
fastformat::write(result, name, age); // FastFormat.Write

4. Verwendung der {fmt}-Bibliothek

#include <fmt/core.h>

std::string name = "John";
int age = 21;

std::string result = fmt::format("{}{}", name, age);

5. Verwendung von IOStreams

std::string name = "John";
int age = 21;

std::stringstream sstm;
sstm << name << age;
std::string result = sstm.str();

6. Verwendung von 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);

7. Sprintf verwenden

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;

8. Verwendung von integer_to_string von STLSoft

#include <stlsoft/integer_to_string.hpp>

std::string name = "John";
int age = 21;

char numstr[21]; // enough to hold all numbers up to 64-bits
std::string result = name + stlsoft::integer_to_string(numstr, 21, age);

9. Verwenden von winstl::int_to_string()

#include <stlsoft/winstl/int_to_string.hpp>

std::string name = "John";
int age = 21;

std::string result = name + winstl::int_to_string(age);

10 von STLSoft. Verwenden von Poco NumberFormatter

#include <Poco/NumberFormatter.h>

std::string name = "John";
int age = 21;

std::string result = name + Poco::NumberFormatter().format(age);

Das obige ist der detaillierte Inhalt vonWie kann ich einen std::string und eine Ganzzahl in C verketten?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn