如何从char16_t字符串文字中读取双精度?
How to read in a double from a char16_t string literal?
如何仅使用标准的 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);
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何从char16_t字符串文字中读取双精度?
- 程序读取文字或解释变量所需的时间是否更少
- 未使用某些文字读取输入