12

以下の小さなテスト プログラムが出力されます。

SS番号IS = 3039

合計の長さが8になるように、左のゼロを埋めて数字を出力したいと思います。

SS 番号は =00003039 (余分なゼロが埋め込まれていることに注意してください)

以下に示すように、マニピュレータと文字列ストリームを使用してこれを行う方法を知りたいです。ありがとう!

テストプログラム:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{

    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << std::hex << i << '\n';

    std::cout << lTransport.str();

}
4

3 に答える 3

12

ライブラリの setfill および setw マニピュレータを見たことがありますか?

#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';

私が得る出力は次のとおりです。

And SS Number IS =00003039
于 2010-03-02T19:35:11.237 に答える
3

私は使うだろう:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
于 2010-03-02T19:40:35.590 に答える
1

次のようにsetwおよびsetfill関数を使用できます。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{    
    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';    
    std::cout << lTransport.str();  // prints And SS Number IS =00003039    
}
于 2010-03-02T19:43:09.483 に答える