http://en.cppreference.com/w/cpp/utility/to_chars
Reference does not say anything about that, but the example is (for me) clearly using a null-terminated string, otherwise how could it know where to end, since std::array::data
returns only a pointer.
#include <iostream>
#include <charconv>
#include <array>
int main()
{
std::array<char, 10> str{};
std::to_chars(str.data(), str.data()+str.size(), 42);
std::cout << str.data();
}
Unfortunately I can't test it myself because AFAIK no compiler supports it yet: https://en.cppreference.com/w/cpp/compiler_support
Edit:
Forgot that str
is initialized with zeros, however question is still relevant.
Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .
Well, yes. C++ strings are always null terminated.
The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.
All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.
The C++17 specification does not state that to_chars
adds a NUL terminator:
All functions named
to_chars
convertvalue
into a character string by successively filling the range [first
,last
) , where [first
,last
) is required to be a valid range. If the memberec
of the return value is such that the value, when converted tobool
, isfalse
, the conversion was successful and the memberptr
is the one-past-the-end pointer of the characters written. Otherwise, the memberec
has the valueerrc::value_too_large
, the memberptr
has the valuelast
, and the contents of the range [first
,last
) are unspecified.
Nothing is stated about a NUL terminator in that paragraph or in the paragraphs that specifically define the behavior of the individual to_chars
overloads. Therefore, it does not write one.
The example works, so long as to_chars
does not produce more than 9 characters. Since str
is initialized to all NUL characters, anything that is not written into str
will be left as NUL characters.
To add to this, the original paper P0067R0 that proposed it explicitly states that the to_chars
functions should not NUL-terminate the strings.
As stated by cpprefrence (your first link)
value is converted to a string as if by std::sprintf in the default ("C") locale.
So no it doesn't add a null terminator, as sprintf
doesn't either (when inserting the values).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With