【C++】0埋めの方法(<iomanip>)

こんてんつ

C++iostreams標準ヘッダー<iomanip>を利用して0埋めを実施する。以下の様々な例を示す。

  • 基本の例とiomanipの理解
  • 変数を利用した例
  • sstream、stringを用いた例

基本の例とiomanipの理解

一番基本のコード

#include<iostream>
#include<iomanip>

using namespace std;

int main() {

    cout << setw(4) << setfill('0') << 11 << endl;

    system("pause>0");
    remove("0");
}

出力

iomanip、setw、setfillを理解するためのコード

setw(4) << setfill('0')の後ろに続く文字に対する0埋めのため、行を跨いでも問題ない。

#include<iostream>
#include<iomanip>

using namespace std;

int main() {

    cout << setw(4) << setfill('0');
    cout << 11 << endl;

    system("pause>0");
    remove("0");
}

setfill('0')を指定しない場合は空欄が出力される。setfill('a')などとすることも可能。

#include<iostream>
#include<iomanip>

using namespace std;

int main() {

    cout << setw(4) << 11 << endl;
    cout << setw(4) << setfill('0') << 11 << endl;
    cout << setw(4) << setfill('a') << 11 << endl;

    system("pause>0");
    remove("0");
}

変数を利用した例

入力

#include<iostream>
#include<iomanip>

using namespace std;

int main() {

    int myVal;
    myVal = 22;
    cout << setw(4) << setfill('0') << myVal << endl;

    system("pause>0");
    remove("0");
}

出力

0022

sstream、stringを用いた例

sstreamを用いて変数的に利用した例

  1. <sstream>をインクルードして、stringstreamを定義する。
  2. 定義したstringstreamに対してsetw(4) << setfill('0')の操作を実施する。
  3. その後、<sstream>.str()関数を用いて文字列を取得して表示する。

入力

#include<iostream>
#include<iomanip>
#include<sstream>

using namespace std;

int main() {

    int myVal;
    myVal = 22;

    stringstream myStream;
    myStream << setw(4) << setfill('0') << myVal;

    cout << myStream.str() << endl;

    system("pause>0");
    remove("0");
}

出力

0022

sstreamを用いて変数的に利用し、更にstring型を定義して再定義した例

上記の操作に加えて、#include<string>によってstring型の定義を実施した方法。

入力

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

using namespace std;

int main() {

    int myVal;
    myVal = 22;

    stringstream myStream;
    myStream << setw(4) << setfill('0') << myVal;

    string myStr;
    myStr = myStream.str();

    cout << myStr << endl;

    system("pause>0");
    remove("0");
}

出力

0022