・文字→数値
#include <string>
int main(){
char c = '1';
// '1'の文字コードは「49」(内部では数値で保存されている)
int i = c - '0';
// '0'の文字コードは「48」
cout << i;
// 1 が出力される。
string s = "123";
int n = s[0] - '0';
cout << n; // 1 が出力される。
}
・文字列→数値
#include <string>
#include <sstream>
int main(){
stringstream ss;
string s = "123";
int n;
ss << s;
ss >> n;
cout << n; // 123 が出力される。
stringstream ss;
string s = "12:34";
int a, b;
char c;
ss << s;
ss >> a >> c >> b;
cout << a; // 12 が出力される。
cout << c; // : が出力される。
cout << b; // 34 が出力される。
}
・文字列の一部→数値
#include <string>
int main(){
string s = "12345";
string sub = s.substr(1,2);
//substr( i 番目から, j 文字 ) と呼び出す。
//以下、上と同様。
}
・数値→文字列
#include <string>
#include <sstream>
int main(){
stringstream ss;
int n = 123;
ss << n;
string s = ss.str();
cout << s; // string型の 123 が出力される。
}
主な手法は以上である。特に文字列⇔数値の変換は関数にまとめておくと、substrで直接呼び出せたり単純に手間が省けたりするので良い。また、こうした変換の手法は一つではなく、ここにあげたものよりも良い方法が存在する可能性は大いにあるので注意して欲しい。