Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

According to https://en.cppreference.com/w/cpp/compiler_support#cpp17, no major vendor yet supports floating point versions of std::to_chars and std::from_chars. I understand that correctly formatting a floating point number is nontrivial, yet implementations exists in the C library. However, these are affected by the environment, which is one of the reasons for adding std::to_chars and std::from_chars to the standard. Wouldn't then an implementation of these function simply come for free if you refactor the C library to depend on common low-level routines that does the actual conversion base conversion into some intermediate format. Then std::to_chars and std::from_chars could use the result more or less directly, and the more high-level API:s in C and C++ (printf, atof, strtod, std::stof, std::to_string) can do some more fancy stuff.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
328 views
Welcome To Ask or Share your Answers For Others

1 Answer

The to/from_chars feature requires that implementations provide round-tripping guarantees (with themselves). Specifically, the following must work:

float f = //get some float
char chars[LOTS_OF_CHARS];
auto result = to_chars(chars, chars + sizeof(chars), f);
float g;
from_chars(chars, result.ptr, g);
assert(f == g);

That guarantee is actually kind of hard to implement, and none of the standard library C or C++ float-to-string-to-float functions have ever provided that guarantee. So you can't just take code from printf/scanf or stof/to_string, rip out the locale stuff, and call that a to/from_chars implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...