LoginSignup
95
75

C++で数値と文字列の相互変換

Last updated at Posted at 2020-11-08

きっかけ

そろそろC++ str to intで調べるのがいやになってきたので、記事に残しておきます。C++のcharクラス・stringクラスとintクラス・その他の数値クラスの相互変換のやり方のまとめです。

#早見表
今回のまとめです

元の型 変換したい型 方法
string 数値 stox( ) ただしxは変換したい型によって変わる
char int int(c-'0')
数値 string to_string( )

stox()関数の詳細です

変換する関数
int stoi
long long stoll
double stod
float stof
long stol
long double stold
unsigned long stoul
unsigned long long stoull

#string to int
string型からint型に変換したい時はstoi()関数を使う。

strtoint.cpp
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]){
    string S = "123";
    int N = stoi(S);
    cout<<"num:"<<N<<" type:"<<typeid(N).name()<<endl;
}

出力は次のようになる。型がintだとiと出力されるらしい。詳しくはC++11のtypeinfoについてを参照。

num:123 type:i

stringから任意の数値型に変換する関数は次の通り。よく使う順。

変換する関数
int stoi
long long stoll
doulbe stod
float stof
long stol
long double stold
unsigned long stoul
unsigned long long stoull

#char to int
stringの文字を1文字ずつ取得してintに変換したい時がある。しかし、stoi()はchar型に対応していない。char型をint型に変換するには、文字コードの引き算を行う必要がある。他にやり方は見つからなかった。

chartoint.cpp
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]){
	string S = "456";
	for(int i=0;i<3;i++){
		int N = int(S[i]-'0');
	    cout<<"num:"<<N<<" type:"<<typeid(N).name()<<endl;
	}
}

出力は次のようになる。

num:4 type:i
num:5 type:i
num:6 type:i

#int to string
数値型をstring型にしたい時はto_string()関数を使う。

inttostr.cpp
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]){
	int N = 789;
	string S = to_string(N);
    cout<<"str:"<<S<<" type:"<<typeid(S).name()<<endl;
}

出力は次のようになる。多分コンパイラのせいかバージョンのせいで、stringのtypeinfo.name()がうまく働いていないが、basic_stringという文字があるのでちゃんとstringになっているはずである。

str:789 type:NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

#まとめ
C++ 文字列 数値と調べなくてもよくなりそうです。

元の型 変換したい型 方法
string 数値 stox( ) ただしxは変換したい型によって変わる
char int int(c-'0')
数値 string to_string( )
95
75
3

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
95
75