개요
- to_chars
- 정수 혹은 부동 소수점 값을 문자 시퀀스로 변환
- from_chars
- 문자 시퀀스를 정수 또는 부동 소수점 값으로 변환
예제
- 코드
#include <array>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
void to_chars_test(auto... format) {
array<char, 10> a;
auto result = to_chars(a.data(), a.data() + a.size(), format...);
if (result.ec == errc()) {
cout << string_view(a.data(), result.ptr - a.data()) << endl;
} else {
cout << make_error_code(result.ec).message() << endl;
}
}
void from_chars_test(string s, auto type, auto... format) {
decltype(type) result = 0;
auto [ptr,
ec]{from_chars(s.data(), s.data() + s.size(), result, format...)};
if (ec == errc()) {
cout << "result : (" << result << "), ptr : (" << ptr << ")" << endl;
} else {
cout << make_error_code(ec).message() << endl;
}
}
int main() {
to_chars_test(10);
to_chars_test(10, 16);
to_chars_test(+11);
to_chars_test(-11);
to_chars_test(3.14);
to_chars_test(3.14, chars_format::fixed);
to_chars_test(-3.14);
to_chars_test(-3.14, chars_format::scientific);
to_chars_test(12345678900);
cout << "------" << endl;
from_chars_test("10", int());
from_chars_test("+10", int());
from_chars_test("-10", int());
from_chars_test("AB", int(), 16);
from_chars_test("11 abc", int());
from_chars_test("3.14", int());
from_chars_test("3.14", double());
from_chars_test("12345678900", int());
return 0;
}
- 실행 결과
10
a
11
-11
3.14
3.14
-3.14
-3.14e+00
Value too large for defined data type
------
result : (10), ptr : ()
Invalid argument
result : (-10), ptr : ()
result : (171), ptr : ()
result : (11), ptr : ( abc)
result : (3), ptr : (.14)
result : (3.14), ptr : ()
Numerical result out of range