developer tip

std :: string과 int를 연결하는 방법은 무엇입니까?

copycodes 2020. 10. 2. 22:49
반응형

std :: string과 int를 연결하는 방법은 무엇입니까?


정말 간단 할 거라고 생각했지만 약간의 어려움이 있습니다. 만약 내가 가지고 있다면

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

단일 문자열을 얻기 위해 어떻게 결합 "John21"합니까?


알파벳순 :

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

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. 안전하지만 느립니다. Boost 필요 (헤더 전용) 대부분 / 모든 플랫폼
  2. 안전하며 C ++ 11이 필요합니다 ( to_string () 은 이미에 포함되어 있습니다 #include <string>)
  3. 안전하고 빠릅니다. 컴파일 해야하는 FastFormat이 필요 합니다. 대부분 / 모든 플랫폼
  4. ( 동감 )
  5. 안전하고 빠릅니다. 컴파일하거나 헤더 전용 모드에서 사용할 수 있는 {fmt} 라이브러리 가 필요 합니다. 대부분 / 모든 플랫폼
  6. 안전하고 느리고 장황합니다. 필요 #include <sstream>(표준 C ++에서)
  7. 부서지기 쉬우 며 (충분히 큰 버퍼를 제공해야 함) 빠르고 장황합니다. itoa ()는 비표준 확장이며 모든 플랫폼에서 사용 가능하다고 보장 할 수 없습니다.
  8. 부서지기 쉬우 며 (충분히 큰 버퍼를 제공해야 함) 빠르고 장황합니다. 아무것도 필요하지 않습니다 (표준 C ++). 모든 플랫폼
  9. 깨지기 쉬움 (충분히 큰 버퍼를 제공해야 함), 아마도 가장 빠른 변환 , 장황함; STLSoft 필요 (헤더 전용) 대부분 / 모든 플랫폼
  10. safe-ish ( 단일 문에서 int_to_string () 호출을 두 개 이상 사용하지 않음 ), 빠름; STLSoft 필요 (헤더 전용) Windows 전용
  11. 안전하지만 느립니다. Poco C ++ 가 필요합니다 . 대부분 / 모든 플랫폼

C ++ 11에서는 다음과 같이 사용할 수 있습니다 std::to_string.

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

Boost가있는 경우를 사용하여 정수를 문자열로 변환 할 수 있습니다 boost::lexical_cast<std::string>(age).

또 다른 방법은 stringstream을 사용하는 것입니다.

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

세 번째 방법은 사용하는 것 sprintf또는 snprintfC 라이브러리에서.

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

다른 포스터는 사용 제안했다 itoa. 이것은 표준 함수가 아니므로 코드를 사용하면 이식 할 수 없습니다. 이를 지원하지 않는 컴파일러가 있습니다.


#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

http://www.research.att.com/~bs/bs_faq2.html 에서 뻔뻔스럽게 도난당했습니다 .


이것이 가장 쉬운 방법입니다.

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

C ++ 11이있는 경우 std::to_string.

예:

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

name += std::to_string(age);

std::cout << name;

산출:

John21

가장 간단한 대답은 sprintf함수 를 사용하는 것 같습니다.

sprintf(outString,"%s%d",name,age);

#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

그러면 사용법은 다음과 같습니다.

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [및 테스트 : p]


이 문제는 여러 가지 방법으로 수행 할 수 있습니다. 두 가지 방법으로 보여 드리겠습니다.

  1. 를 사용하여 숫자를 문자열로 변환합니다 to_string(i).

  2. 문자열 스트림 사용.

    암호:

    #include <string>
    #include <sstream>
    #include <bits/stdc++.h>
    #include <iostream>
    using namespace std;
    
    int main() {
        string name = "John";
        int age = 21;
    
        string answer1 = "";
        // Method 1). string s1 = to_string(age).
    
        string s1=to_string(age); // Know the integer get converted into string
        // where as we know that concatenation can easily be done using '+' in C++
    
        answer1 = name + s1;
    
        cout << answer1 << endl;
    
        // Method 2). Using string streams
    
        ostringstream s2;
    
        s2 << age;
    
        string s3 = s2.str(); // The str() function will convert a number into a string
    
        string answer2 = "";  // For concatenation of strings.
    
        answer2 = name + s3;
    
        cout << answer2 << endl;
    
        return 0;
    }
    

+출력 연산자가있는 모든 항목을 연결하는 데 사용하려면 다음 템플릿 버전을 제공 할 수 있습니다 operator+.

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

그런 다음 간단한 방법으로 연결을 작성할 수 있습니다.

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

산출:

the answer is 42

이것은 가장 효율적인 방법은 아니지만 루프 내에서 많은 연결을 수행하지 않는 한 가장 효율적인 방법이 필요하지 않습니다.


MFC를 사용하는 경우 CString을 사용할 수 있습니다.

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);

Managed C ++에는 문자열 포맷터도 있습니다.


std :: ostringstream은 좋은 방법이지만 때로는이 추가 트릭이 서식을 한 줄로 변환하는 데 편리 할 수 ​​있습니다.

#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
    static_cast<std::ostringstream&>(          \
        std::ostringstream().flush() << tokens \
    ).str()                                    \
    /**/

이제 다음과 같은 문자열 형식을 지정할 수 있습니다.

int main() {
    int i = 123;
    std::string message = MAKE_STRING("i = " << i);
    std::cout << message << std::endl; // prints: "i = 123"
}

이 질문에 찬성하여 Qt 관련 질문이 종료되었으므로 다음은 Qt를 사용하여 수행하는 방법입니다.

QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);

The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.


There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format

#include <boost/format.hpp>
#include <string>
int main()
{
    using boost::format;

    int age = 22;
    std::string str_age = str(format("age is %1%") % age);
}

and Karma from Boost.Spirit (v2)

#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
    using namespace boost::spirit;

    int age = 22;
    std::string str_age("age is ");
    std::back_insert_iterator<std::string> sink(str_age);
    karma::generate(sink, int_, age);

    return 0;
}

Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.


Common Answer: itoa()

This is bad. itoa is non-standard, as pointed out here.


Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.

#include <iostream>
#include <locale>
#include <string>

template <class Facet>
struct erasable_facet : Facet
{
    erasable_facet() : Facet(1) { }
    ~erasable_facet() { }
};

void append_int(std::string& s, int n)
{
    erasable_facet<std::num_put<char,
                                std::back_insert_iterator<std::string>>> facet;
    std::ios str(nullptr);

    facet.put(std::back_inserter(s), str,
                                     str.fill(), static_cast<unsigned long>(n));
}

int main()
{
    std::string str = "ID: ";
    int id = 123;

    append_int(str, id);

    std::cout << str; // ID: 123
}

  • std::ostringstream
#include <sstream>

std::ostringstream s;
s << "John " << age;
std::string query(s.str());
  • std::to_string (C++11)
std::string query("John " + std::to_string(age));
  • boost::lexical_cast
#include <boost/lexical_cast.hpp>

std::string query("John " + boost::lexical_cast<std::string>(age));

There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:

char intToChar(int num)
{
    if (num < 10 && num >= 0)
    {
        return num + 48;
        //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
    }
    else
    {
        return '*';
    }
}

string intToString(int num)
{
    int digits = 0, process, single;
    string numString;
    process = num;

    // The following process the number of digits in num
    while (process != 0)
    {
        single  = process % 10; // 'single' now holds the rightmost portion of the int
        process = (process - single)/10;
        // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
        // The above combination eliminates the rightmost portion of the int
        digits ++;
    }

    process = num;

    // Fill the numString with '*' times digits
    for (int i = 0; i < digits; i++)
    {
        numString += '*';
    }


    for (int i = digits-1; i >= 0; i--)
    {
        single = process % 10;
        numString[i] = intToChar ( single);
        process = (process - single) / 10;
    }

    return numString;
}

You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

Output:  John5

With the {fmt} library:

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

A subset of the library is proposed for standardization as P0645 Text Formatting and, if accepted, the above will become:

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

Disclaimer: I'm the author of the {fmt} library.

참고URL : https://stackoverflow.com/questions/191757/how-to-concatenate-a-stdstring-and-an-int

반응형