LoginSignup
3
4

More than 5 years have passed since last update.

int から 文字列に変換

Last updated at Posted at 2014-04-22

int型からcharの配列/std::stringに変換

ファイル名に日付を使いたいときなど、ctimeヘッダ内のtm構造体から日時を取得するとintで返ってくるのでそのまま使えない。
char型への通常のキャストでは数値に相当する文字にフォーマットされるので、そのままキャストして使えない。
 例:整数値10 → 改行文字 (アスキーコード相当の場合)

今回はソースコード簡潔にするため年だけを使った。

まず今年を表す数値を求める。
現実にはロケールを考慮する必要があると思うが、分からない。誰か教えて(´・ω・`)

   #include <ctime>

   tm toady;
   time_t t_val;

   t_val = std::time( NULL );
   localtime_s( &today, &t_val );

   int year = today.tm_year + 1900   // 2014年

ここから数値2014を各桁に分割する。
分割方法は10で割った余り(1の位)を常に求め、10で割って桁を縮めた。

    while( year >= 1 ) {
        year % 10;
        year = year / 10;
    }

上の例は余りを計算しただけで結果を破棄しているが、次にこれを利用する。
1桁のみ取得なので必ず1桁の数値になる。
よって文字[0:9]の範囲を部分として寄せ集める。

文字列定数"0123456789"を配列に格納すれば添字0が文字'0'、添字1が文字'1'なので都合がよさそうだ。

    #include <string>
    #include <vector>

    // 添字(数値)と各文字列が1対1に対応するオブジェクトを用意
    const char number[11] = "0123456789";

    std::vector<char> date;
    int index = 0;

    while( year >= 1 ) {
         // 1の位を求める
         index = year % 10;
         // 1の位をchar型の動的配列に積み上げる
         date.push_back( number[index] );

         year = year / 10;
   }

   /* 1の位から順に格納したため逆順にする */

   vector<char>::reverse_iterator itr;
   itr = date.rbegin();

   string today = "";
   // リバース・イテレータを一つづつ進めて文字列に足し込む
   for( int i = 0; i < date.size(); ++i ) {
        today += *itr;
        ++itr;
   }

汎用性の高いstd::stringになったのでC文字列にも変換できるようになった。

today.c_str();

先頭ポインタも取れるようになった

const char* head_ptr = today.data();

もっといい書き方がありそう(´・ω・`)

3
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4