Troskyvs
Troskyvs

Reputation: 8077

What's c++11/14/17 equivalence to C function of ltoa/itoa?

C++11/14/17 provides functions from string to int/long, but what about vice versa?

I wish to convert an integer to a binary string and then prints it, like:

int i = 127;
char buf[20];
ltoa(i, buf, 2);
printf("%032s\n", buf);

I can see

00000000000000000000000001111111

Currently I could only use C style function on different platforms, like on linux I've ltoa, on windows, _itoa_s (cannot be more ugly) ...

But what about c++?

Thanks a lot.

Upvotes: 1

Views: 1170

Answers (1)

L. F.
L. F.

Reputation: 20619

In C++17, we have to_chars:

int i = 127;
char buf[20];
auto [p, e] = std::to_chars(buf, buf + 20, i, 2);

The first two parameters are of type char* and denote the buffer. The third parameter is the number. The last parameter is the base. This is essentially the same with ltoa.

p is the past-the-end pointer. e is the error code. Note that the string is not null-terminated.

(live demo)

Upvotes: 2

Related Questions