1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++のsprintfの使い方: printf を文字列に代入できる!

Last updated at Posted at 2019-08-16

はじめに

printf で出力する文字列を変数に代入したいことって良くありますよね!!
ここではsprintf を用いてprintfで出力する文字列を変数に代入します

本題

イメージとして下記のようなことがしたいとします

string s = printf("%06d%06d", tmp1, tmp2);

これを下記のように書き換えることによって printf での出力を代入することができます.

sprintf(s, "%06d%06d", tmp1, tmp2);

もう少し細かく説明していきます.
sprintf は第一引数のchar 型です.

string ではなく char の配列を準備します
(注意: 文字列の最後は '\0' が入るため予定しているサイズより1個大きいサイズを準備してください)
ここまできたら, あとはもう簡単です.
sprintf((char型配列), (いつものprintfの書き方)) で
文字列を代入することができます.
下記はサンプルプログラムです.

exsample.cpp
# include<bits/stdc++.h>
using namespace std;

int main(){
    char s[13]; 
    int tmp1=123, tmp2=45;
    sprintf(s, "%06d%06d", tmp1, tmp2);
    cout << s << endl;
}
exsample_output.txt
000123000045

もちろん多次元配列でも代入できます.

exsample2.cpp
# include<bits/stdc++.h>
using namespace std;

int main(){
    char s[3][13];
    int tmp1=0, tmp2=0;
    for(int i=0; i<3; i++){
    	tmp1+=2;
    	tmp2+=3;
    	sprintf(s[i], "%06d%06d", tmp1, tmp2);
    }
    for(int i=0; i<3; i++){
    	cout << s[i] <<endl;
    }
}
exsample2_output.txt
000002000003
000004000006
000006000009
1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?