C++に於けるatoiやsprintf、coutでprintfのような書式指定

よく使うのによく忘れるので備忘録。CのatoiとかsprintfのC++風の書き方。

atoi

まずCでatoi関数を使うプログラム。が必要です。

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	char str[10];
	scanf("%9s", str);
	printf("%d\n", atoi(str));
	return 0;
}

かなり適当です。10文字以上入力した場合にバッファに文字列が残るのは気にしない方針で。
これをC++風に書くと次のようになります。

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

using namespace std;

int main(void) {
	string str;
	int n;
	cin >> str;
	istringstream istr(str);
	istr >> n;
	cout << n << endl;
	return 0;
}

変数名が酷いのは置いておいて、が必要です。atoiというよりsscanfに近いらしいです。istringstreamにコンストラクタではなく後から文字列を渡すときはistr.str(文字列);とします。

sprintf

次にsprintfをC++っぽく書いてみます。
まず、Cでsprintfを使うプログラム。

#include <stdio.h>

int main(void) {
	int n;
	char str[16];
	scanf("%d", &n);
	sprintf(str, "n = %d\n", n);
	printf(str);
	return 0;
}

このプログラムをC++風に書くと、次のようになります。

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

using namespace std;

int main(void) {
	int n;
	string str;
	ostringstream ostr;
	cin >> n;
	ostr << "n = " << n;
	cout << ostr.str() << endl;
	return 0;
}

coutと同じように使えます。
istringstreamとostringstreamを継承したstringstreamというクラスを使えば、1つの変数で両方できます。

coutでprintfのような書式指定

例えばCでprintfのいろいろな書式指定を使ったプログラム。

#include <stdio.h>

int main(void) {
	int n = 123;
	double d = 12.345;
	printf("%5d\n", n);
	printf("%05d\n", n);
	printf("%X\n", n);
	printf("%.2f\n", d);
	return 0;
}

これをcoutを使って書くと次のようになります。

#include <iostream>
#include <iomanip>

using namespace std;

int main(void ) {
	int n = 123;
	double d = 12.345;
	cout << setw(5) << n << endl;
	cout << setfill('0') << setw(5) << n << endl;
	cout << hex << uppercase << n << endl;
	cout << setprecision(2) << setiosflags(ios::fixed) << d << endl;
	return 0;
}

が必要です。他にももっとたくさんのマニピュレータがあるので必要があれば調べてみてください。