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());
답변
boost::lexical_cast<std::string>(yourint)
…에서 boost/lexical_cast.hpp
std :: ostream을 지원하는 모든 작업에 적합하지만, 예를 들어 itoa
심지어 stringstream 또는 scanf보다 빠릅니다.
답변
잘 알려진 방법은 스트림 연산자를 사용하는 것입니다.
#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();
}
답변
std::to_string
C ++ 11에서 사용할 수없는 경우 cppreference.com에 정의 된대로 작성할 수 있습니다.
std::string to_string( int value )
부호있는 십진 정수를std::sprintf(buf, "%d", value)
충분히 큰 buf를 생성 할 내용과 동일한 내용의 문자열로 변환합니다 .
이행
#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에, 그리고.
답변
비표준 기능이지만 가장 일반적인 컴파일러에서 구현됩니다.
int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);
최신 정보
C ++ 11은 몇 가지 std::to_string
오버로드를 도입했습니다 (기본은 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;
}