如何从char16_t字符串文字中读取双精度?



如何仅使用标准的 C++11 功能从 char16_t 字符串 (char16_t *( 中读取双精度?

我试过这个:

#include <iostream>
#include <sstream>
#include <string>
double char16_to_double( const char16_t* s )
{
double n = 0;
std::basic_stringstream<char16_t> ss( s );
ss >> n;
return n;
}
int main()
{
try {
double n = char16_to_double( u"0.1" );
std::cout << "Value of n: " << n << std::endl;
} catch( ... ) {
std::cout << "Exception!" << std::endl;   
}
return 0;
}

但是,当我使用 g++-7 编译它时,它会在 https://cpp.sh 中抛出异常,或者导致 0,而不是 0.1。正确的方法是什么?

我发现的一种可能的解决方案是通过std::wstring_convert将char16_t(UTF16 编码(转换为字符字符串:

#include <codecvt>
#include <iostream>
#include <locale>
#include <sstream>
#include <string>
double char16_to_double( const char16_t* s )
{
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t > my_conv;
double n = 0;
std::istringstream ss( my_conv.to_bytes( s ).c_str() );
ss >> n;
return n;
}
int main()
{
try {
double n = char16_to_double( u"0.1" );
std::cout << "Value of n: " << n << std::endl;
} catch( ... ) {
std::cout << "Exception!" << std::endl;
}
return 0;
}

如果有人有更直接的解决方案,我会对此持开放态度。

你可以将其转换为字符串并使用stdlib.h的stod

double char16_to_double( const char16_t* s ) {
std::string str = "";
for(size_t i = 0; s[i] != 0; i++) {
str += s[i];
}
return stod(str);
}

最新更新