この質問は毎週聞かれるので、このFAQは多くのユーザーに役立つかもしれません。
C++ で整数を文字列に変換する方法
C++ で文字列を整数に変換する方法
C++ で浮動小数点数を文字列に変換する方法
C++ で文字列を浮動小数点数に変換する方法
標準ではC++11
、文字列から数値への変換とその逆が標準ライブラリに組み込まれています。以下の機能はすべて<string>
(21.5 項に従って) に存在します。
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
これらはそれぞれ文字列を入力として取り、それを数値に変換しようとします。数値データがない、または数値が型の範囲外であるなどの理由で、有効な数値を構築できなかった場合は、例外がスローされます (std::invalid_argument
またはstd::out_of_range
)。
変換が成功し、idx
でない場合0
、idx
デコードに使用されなかった最初の文字のインデックスが含まれます。これは、最後の文字の後ろのインデックスである可能性があります。
最後に、整数型では基数を指定できます。9 より大きい数字の場合、アルファベットが想定されます (a=10
までz=35
)。浮動小数点数、符号付き整数、および符号なし整数についてここで解析できる正確なフォーマットに関する詳細情報を見つけることができます。
std::wstring
最後に、各関数には、最初のパラメーターとしてa を受け入れるオーバーロードもあります。
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
これらはより簡単です。適切な数値型を渡すと、文字列が返されます。書式設定オプションについては、C++03 の stringream オプションに戻り、ストリーム マニピュレータを使用する必要があります。これについては、こちらの他の回答で説明しています。
コメントに記載されているように、これらの関数はデフォルトの仮数精度にフォールバックしますが、これは最大精度ではない可能性があります。アプリケーションにさらに精度が必要な場合は、他の文字列フォーマット手順に戻ることも最善です。
という名前の同様の関数も定義されておりto_wstring
、これらは を返しますstd::wstring
。
itoa
またはitof
関数は非標準であり、移植性がないため、使用しないでください。文字列ストリームを使用する
#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
文字列ストリームを使用して、浮動小数点数を文字列に変換したり、必要に応じて文字列をフォーマットしたりすることもできます。cout
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
や functionsなどstd::endl
のストリーム マニピュレータを、文字列ストリームとまったく同じ方法で使用できます。std::hex
std::setw()
std::setprecision()
cout
std::ostringstream
と混同しないstd::ostrstream
でください。後者は非推奨です
ブースト レキシカル キャストを使用します。ブーストに慣れていない場合は、この lexical_cast のような小さなライブラリから始めることをお勧めします。ブーストとそのドキュメントをダウンロードしてインストールするには、ここにアクセスしてください。ブーストは C++ 標準にはありませんが、ブーストの多くのライブラリは最終的に標準化され、ブーストは最高の C++ ライブラリと広く見なされています。
レキシカル キャストは下にストリームを使用するため、基本的にこのオプションは前のものと同じですが、冗長性が低くなります。
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
C から継承された最も軽量なオプションは、関数atoi
(整数 (アルファベットから整数)atof
用) および (浮動小数点値 (アルファベットから浮動小数) 用) です。これらの関数は C スタイルの文字列を引数 ( const char *
) として受け取るため、その使用法はC++ の適切な実践とは言えません。cplusplus.comには、atoiとatofの両方について、不適切な入力があった場合の動作など、わかりやすいドキュメントがあります。ただし、リンクには、入力数値が大きすぎてターゲット型に収まらない場合の標準によると、動作が未定義であるというエラーが含まれています。
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
文字列ストリーム (今回は入力文字列ストリームistringstream
) を使用します。繰り返しますが、 istringstream は と同じように使用されcin
ます。istringstream
繰り返しますが、 と混同しないでくださいistrstream
。後者は非推奨です。
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
ブースト レキシカル キャストを使用します。
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
不正な入力の場合、lexical_cast
タイプの例外をスローしますboost::bad_lexical_cast
この便利なクラスを StackOverflow のどこかから盗んで、ストリーミング可能なものをすべて文字列に変換しました。
// make_string
class make_string {
public:
template <typename T>
make_string& operator<<( T const & val ) {
buffer_ << val;
return *this;
}
operator std::string() const {
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
そして、それを次のように使用します。
string str = make_string() << 6 << 8 << "hello";
かなり気の利いた!
また、この関数を使用して文字列をストリーミング可能なものに変換しますが、数値を含まない文字列を解析しようとすると安全ではありません。 (そして、最後のものほど賢くはありません)
// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
std::stringstream buf;
buf << str;
RETURN_TYPE val;
buf >> val;
return val;
}
使用:
int x = parse_string<int>("78");
wstring のバージョンも必要になる場合があります。