programing

int를 std::string으로 변환

jooyons 2023. 8. 18. 22:30
반응형

int를 std::string으로 변환

int를 문자열로 변환하는 가장 짧은 방법은 무엇입니까, 가급적이면 인라인이 가능합니까?stl 및 boost를 사용한 답변을 환영합니다.

C++11에서 std::to_string을 사용할 수 있습니다.

int i = 3;
std::string str = std::to_string(i);
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());

C++11 이전의 잘 알려진 방법은 스트림 연산자를 사용하는 것입니다.

#include <sstream>

std::ostringstream s;
int i;

s << i;

std::string converted(s.str());

물론 템플릿 기능을 사용하여 모든 유형에 대해 일반화할 수 있습니다 ^^

#include <sstream>

template<typename T>
std::string toString(const T& value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}

boost::lexical_cast<std::string>(yourint)부터boost/lexical_cast.hpp

std:: ostream 지원으로 모든 작업이 가능하지만, 예를 들어 다음과 같이 빠르지는 않습니다.itoa

stringstream 또는 scanf보다 더 빠른 것으로 보입니다.

C++11에서 사용할 수 없는 경우 cppreference.com 에 정의된 대로 작성할 수 있습니다.

std::string to_string( int value )부호 있는 10진수 정수를 다음과 같은 내용의 문자열로 변환합니다.std::sprintf(buf, "%d", value)충분히 큰 버프를 생산할 수 있습니다.

실행

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

그것으로 더 많은 것을 할 수 있습니다.그냥 사용하기"%g"플로트 또는 더블을 문자열로 변환하려면 사용"%x"int를 16진수 표현으로 변환하는 등의 작업을 수행합니다.

비표준 기능이지만 대부분의 일반적인 컴파일러에서 구현됩니다.

int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);

갱신하다

C++11은 몇 가지 오버로드를 도입했습니다(기본값은 기본값 10).

다음 매크로는 일회용만큼 작지 않습니다.ostringstream또는boost::lexical_cast.

그러나 코드에서 문자열로의 변환이 반복적으로 필요한 경우, 이 매크로는 매번 문자열 스트림이나 명시적 캐스팅을 직접 처리하는 것보다 사용하기에 더 우아합니다.

또한 지원되는 모든 것을 변환하기 때문에 매우 다양합니다.operator<<()조합하여라도

정의:

#include <sstream>

#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()

설명:

std::dec부작용이 없는 익명의 사람들을 만드는 방법입니다.ostringstream일반적으로.ostream그렇게operator<<()함수 조회는 모든 유형에 대해 올바르게 작동합니다. (그렇지 않으면 첫 번째 인수가 포인터 유형인 경우 문제가 발생합니다.)

dynamic_cast형식을 다시 로 반환합니다.ostringstream당신이 전화할 수 있습니다.str()그 위에

사용:

#include <string>

int main()
{
    int i = 42;
    std::string s1 = SSTR( i );

    int x = 23;
    std::string s2 = SSTR( "i: " << i << ", x: " << x );
    return 0;
}

이 함수를 사용하여 다음을 변환할 수 있습니다.int로.std::string포함한 후에<sstream>:

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}

하는 동안에std::to_stringC++20으로 시작하는 간단한 도구로, 를 포함할 수 있습니다. 를 사용하면 보다 정교한 대화가 가능합니다.int로.string:

#include <iostream>
#include <locale>
#include <format>

int main()
{
    using std::cout, std::endl;

    auto const n = 42;
    cout << std::format("{}", n) << endl;
    cout << std::format("{:d}", n) << endl;
    cout << std::format("{:#x}", n) << endl;
    cout << std::format("{:#o}", n) << endl;
    cout << std::format("{:#b}", n) << endl;
}

출력:

42
42
0x2a
052
0b101010

프로젝트에 itoa 구현을 포함할 수 있습니다.
std::string으로 작업하기 위해 수정된 내용입니다. http://www.strudel.org.uk/itoa/

내가 가지고 있다고 가정해봐요.integer = 0123456789101112이 는 이, 이, 정, 에 의해 될 수 .stringstream학생들

C++의 코드는 다음과 같습니다.

   #include <bits/stdc++.h>
   using namespace std;
   int main()
   {
      int n,i;
      string s;
      stringstream st;
      for(i=0;i<=12;i++)
      {
        st<<i;
      }
      s=st.str();
      cout<<s<<endl;
      return 0;

    }
#include <string>
#include <stdlib.h>

여기, 문자열로 변환하는 또 다른 쉬운 방법이 있습니다.

int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());

더 많은 방법을 보려면 이 링크를 방문하십시오. https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/

언급URL : https://stackoverflow.com/questions/4668760/converting-an-int-to-stdstring

반응형