답변:
사용 .str () - 방법 :
기본 문자열 개체의 내용을 관리합니다.
1)를 호출하는 것처럼 기본 문자열의 복사본을 반환합니다
rdbuf()->str().2)
rdbuf()->str(new_str)... 를 호출하여 기본 문자열의 내용을 대체합니다 .노트
str에 의해 반환 된 기본 문자열의 복사본은 표현식의 끝에서 파괴되는 임시 객체이므로 (예 :)
c_str()의 결과를 직접 호출 하면 댕글 링 포인터가 생성됩니다.str()auto *ptr = out.str().c_str();
std::stringstream::str() 당신이 찾고있는 방법입니다.
와 함께 std::stringstream:
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::stringstream ss;
ss << NumericValue;
return ss.str();
}
std::stringstream보다 일반적인 도구입니다. std::ostringstream이 특정 작업에 대해 더 전문화 된 클래스 를 사용할 수 있습니다 .
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::ostringstream oss;
oss << NumericValue;
return oss.str();
}
std::wstring문자열 유형으로 작업 하는 경우 std::wstringstream또는 std::wostringstream대신 선호해야합니다 .
template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
std::wostringstream woss;
woss << NumericValue;
return woss.str();
}
문자열의 문자 유형을 런타임에서 선택할 수 있도록하려면이를 템플릿 변수로 만들어야합니다.
template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
std::basic_ostringstream<CharType> oss;
oss << NumericValue;
return oss.str();
}
위의 모든 방법에 대해 다음 두 개의 헤더 파일을 포함해야합니다.
#include <string>
#include <sstream>
NumericValue위 예제 의 인수 는 각각 및 인스턴스 와 함께 std::string또는 std::wstring로 전달 될 수도 있습니다 . 가 숫자 값일 필요는 없습니다 .std::ostringstreamstd::wostringstreamNumericValue