use*_*220 0 c++ character type-conversion c++17
我正在尝试使用 std::from_chars 将字符串转换为双精度,但是当涉及指数数字时,我无法与 strtod 对齐。再现者:
#include <string>
#include <iostream>
#include <charconv>
void xxx(std::string const A){
double x;
std::from_chars(&A[0],&A.back(),x,std::chars_format::scientific);
printf("%s,%.17g\n",A.c_str(),x);
}
void yyy(std::string const A){
printf("%s,%.17g\n",A.c_str(),strtod(&A[0],NULL));
}
int main(){
xxx(std::string("0.9226e-01"));
yyy(std::string("0.9226e-01"));
xxx(std::string("0.9226e-10"));
yyy(std::string("0.9226e-10"));
}
Run Code Online (Sandbox Code Playgroud)
产生输出
0.9226e-01,0.92259999999999998
0.9226e-01,0.092259999999999995
0.9226e-10,0.092259999999999995
0.9226e-10,9.226e-11
Run Code Online (Sandbox Code Playgroud)
我想说 strtod 会产生正确的结果。
很高兴得知我弄错了。
平台:linux g++版本:12.2
谢谢,圣诞快乐
分析字符序列[first,last)的模式如下所述。
右括号表示last被排除。因此,正在处理的实际数据std::from_chars(&A[0], &A.back(), ...)是
"0.9226e-0"
"0.9226e-1"
Run Code Online (Sandbox Code Playgroud)
正确的调用方式:
void xxx(std::string const A){
double x;
std::from_chars(A.begin(), A.end(), x,std::chars_format::scientific);
printf("%s,%.17g\n", A.c_str(),x);
}
Run Code Online (Sandbox Code Playgroud)
或者
void xxx(std::string const A){
double x;
std::from_chars(&A[0], &A[0] + A.size(), x,std::chars_format::scientific);
printf("%s,%.17g\n", A.c_str(),x);
}
Run Code Online (Sandbox Code Playgroud)