Program Club

% 02d와 std :: stringstream?

proclub 2020. 12. 12. 11:40
반응형

% 02d와 std :: stringstream?


나는 출력에 정수 원하는 std::stringstream에 해당하는 형식 printf의를 %02d. 이것을 달성하는 더 쉬운 방법이 있습니까?

std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;

stringstream(의사 코드)와 같은 일종의 형식 플래그를으로 스트리밍 할 수 있습니까?

stream << flags("%02d") << value;

당신은에서 표준 조작기를 사용할 수 <iomanip>있지만, 모두 않는 깔끔한 일이없는 fill그리고 width한 번에는 :

stream << std::setfill('0') << std::setw(2) << value;

스트림에 삽입 될 때 두 기능을 모두 수행하는 자체 객체를 작성하는 것은 어렵지 않습니다.

stream << myfillandw( '0', 2 ) << value;

struct myfillandw
{
    myfillandw( char f, int w )
        : fill(f), width(w) {}

    char fill;
    int width;
};

std::ostream& operator<<( std::ostream& o, const myfillandw& a )
{
    o.fill( a.fill );
    o.width( a.width );
    return o;
}

당신이 사용할 수있는

stream<<setfill('0')<<setw(2)<<value;

표준 C ++에서는 그렇게 더 잘할 수 없습니다. 또는 Boost.Format을 사용할 수 있습니다.

stream << boost::format("%|02|")%value;

어떤 종류의 형식 플래그를으로 스트리밍 할 수 stringstream있습니까?

불행히도 표준 라이브러리는 형식 지정자를 문자열로 전달하는 것을 지원하지 않지만 fmt 라이브러리를 사용하여이를 수행 할 수 있습니다 .

std::string result = fmt::format("{:02}", value); // Python syntax

또는

std::string result = fmt::sprintf("%02d", value); // printf syntax

구성 할 필요조차 없습니다 std::stringstream. format함수는 문자열을 직접 반환합니다.

면책 조항 : 저는 fmt 라이브러리 의 저자입니다 .

참고 URL : https://stackoverflow.com/questions/2839592/equivalent-of-02d-with-stdstringstream

반응형