std::wstring を int、long、float、double などの数値型に変換する最良の方法は何ですか?
6 に答える
C ++ 0xでは、次の 関数が導入されてい<string>
ます。
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);
long long stoll (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const wstring& str, size_t* idx = 0, int base = 10);
float stof (const wstring& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
long double stold(const wstring& str, size_t* idx = 0);
idx
str
(変換関数によって設定された)内の変換の終わりへのオプションのnullポインターです。
どちらかを使用boost::lexical_cast<>
:
#include <boost/lexical_cast.hpp>
std::wstring s1(L"123");
int num = boost::lexical_cast<int>(s1);
std::wstring s2(L"123.5");
double d = boost::lexical_cast<double>(s2);
boost::bad_lexical_cast
文字列を変換できない場合、これらは例外をスローします。
もう 1 つのオプションは、Boost Qi (Boost.Spirit のサブライブラリ) を使用することです。
#include <boost/spirit/include/qi.hpp>
std::wstring s1(L"123");
int num = 0;
if (boost::spirit::qi::parse(s1.begin(), s1.end(), num))
; // conversion successful
std::wstring s2(L"123.5");
double d = 0;
if (boost::spirit::qi::parse(s1.begin(), s1.end(), d))
; // conversion successful
Qi を使用すると、lexical_cast よりもはるかに高速ですが、コンパイル時間が長くなります。
一番?
CRT ライブラリ以外のものを使用したくなく、文字列を変換できない場合に 0 を取得することに満足している場合は、エラー処理、ヘッダーを含む複雑な構文を次の方法で節約できます。
std::wstring s(L"123.5");
float value = (float) _wtof( s.c_str() );
それはすべて、あなたが何をしているかに依存します。これがKISSのやり方です!
wstringstream / stringstreamを使用します。
#include <sstream>
float toFloat(const std::wstring& strbuf)
{
std::wstringstream converter;
float value = 0;
converter.precision(4);
converter.fill('0');
converter.setf( std::ios::fixed, std::ios::floatfield );
converter << strbuf;
converter >> value;
return value;
}
文字列ストリームを使用するだけです。忘れないでください#include <sstream>
wchar_t blank;
wstring sInt(L"123");
wstring sFloat(L"123.456");
wstring sLong(L"1234567890");
int rInt;
float rFloat;
long rLong;
wstringstream convStream;
convStream << sInt<<' '<< sFloat<<' '<<sLong;
convStream >> rInt;
convStream >> rFloat;
convStream >> rLong;
cout << rInt << endl << rFloat << endl << rLong << endl;
だから私は Embarcadero を使用していましたが、..... の一部では stoi を使用できなかったので、独自の関数を作成する必要があります。
int string_int(wstring lala){
int numero;
int completo = 0;
int exponente = 1;
int l = 1;
for (int i = 0; i < lala.size(); i++){
numero = 0;
for (int j = 48; j < 57; j++){
if (lala[i] == j){
break;
}
numero++;
}
for (int k = 0; k < lala.size() - l; k++){
exponente *= 10;
}
numero *= exponente;
completo += numero;
exponente = 1;
l++;
}
return completo;
}