0

C では、printf("%+10.5d\n", x); を使用しています。整数 x を出力します。

C++ io マニピュレーター用の小さなテスト ケースを作成しましたが、出力の形式が異なります。

#include <iostream>
#include <iomanip>
#include <cstdio>

int main(void)
{
        int x = 3;
        printf("%+10.5d\n", x);
        std::cout << std::showpos << std::setw(10) << std::setprecision(5) << x << std::endl;
        return 0;
}

出力は次のとおりです。

./テストコマンド
       +00003
           +3

printfと同じ出力を得るために、ここで欠落しているioマニピュレーターはどれですか?

4

4 に答える 4

2

std::setfill
http://www.cplusplus.com/reference/iostream/manipulators/setfill/

短いifステートメントで
((x>0) ? "+" : "" )

それで:
std::cout << ((x>0) ? "+" : "" ) << std::setfill('0') << std::setw(10) << std::setprecision(5) << x << std::endl;

于 2011-05-04T15:43:08.790 に答える
1

boost::format を使用すると、探しているものをより簡潔な形式で取得できます。

http://www.boost.org/doc/libs/release/libs/format/doc/format.html

#include <boost/format.hpp>

int main(void)
{
    int x = 3;
    std::cout << boost::format("%+10.5d") % x << std::endl;
    return 0;
}

sprintf 機能の場合、cout 行をこれに変更できます。

std::string x_string = boost::str(boost::format("%+10.5d") % x);
于 2011-05-04T16:03:55.560 に答える
0

私が得ることができる最も近いものはこれです(注意してくださいstd::internal):

#include <iostream>
#include <iomanip>
#include <cstdio>

int main(void)
{
    int x = 3;
    printf("%+10.5d\n", x);
    std::cout << std::setfill('0') << std::internal << std::showpos << std::setw(10) << std::setprecision(5) << x << std::endl;
    return 0;
}

これはまだ完全には正しくありません:

    +00003
+000000003

しかし、それは改善です。

于 2011-05-04T15:51:19.823 に答える
0

この特定のケースでは、少なくとも多くの作業がなければ、それは不可能だと思います。C++ では (C とは異なり)、 precision整数を出力するときに引数が無視されるため、マニピュレーターだけを使用して必要な効果を得ることができません (また、boost::formatそれもサポートしていません)。おそらく、文字列にフォーマットしてから、 '0'手動でプレフィックスまたは挿入する必要があります。

以前、私はGB_Formatクラスを持っていました (これはネームスペース以前の時代でした) に少し似boost::formatていますが、すべての Posix フォーマット仕様をサポートしていました。機能させるに "%.<i>n</i>d"は、基になるストリーム変換を使用するのではなく、整数変換を自分で実装する必要がありました。次のようなもの:

std::string
fmtInt( int value, int width, int precision )
{
    unsigned            work = (value < 0 ? -value : value);
    std::string         result;
    while ( work != 0 || result.size() < precision ) {
        result += "0123456789"[ work % 10 ];
        work /= 10;
    }
    result += (value < 0 ? '-' : '+');
    while ( result.size() < width ) {
        result += ' ';
    }
    return std::string( result.rbegin(), result.rend() );
}
于 2011-05-04T17:43:03.160 に答える