【C++】stringをint型に変換する
またまたメモ。
最初に文字列として取得して、後々数値で処理する際には必要な過程ですね。
ではいきなりコードに参ります。
コード
#include <cstdio> //sscanf() #include <iostream> #include <string.h> #include <typeinfo> //typeid() using namespace std; int main(){ string x_s = "100"; int x_i; sscanf(x_s.c_str(), "%d", &x_i); cout << "type of x_s :" << typeid(x_s).name() << endl; cout << "type of x_i :" << typeid(x_i).name() << endl; return 0; }
sscanf()を利用するのもいいけれど、参考文献にあるstoi()を利用する手法が一番simpleでとてもよいと思います。