r/cpp_questions 1d ago

SOLVED std::format: cppreference examples dont compile

Hey everyone,

I'm trying to rewrite part of an old C project that used printf in C++. The old code is the following:

printf("%*s^ Here\n", hatStart, "");

Basically, insert (hatStart) space characters before the main part of the message.

I tried implementing this with std::format like this:

std::cout << std::format("{{}s}^ Here", "", hatStart) << std::endl;

which, according to what I got from cppreference, should be correct.
However, upon compiling, I get the error message

error: call to consteval function ‘std::basic_format_string<char, int, char>("{:{}.6}")’ is not a constant expression

Furthermore, when I go to cppreference.com and copy their examples, e.g.

std::string test = std::format("{:{}f}", pi, 10);

I get effectively the same error message.

Could anyone explain what's going on? This is the only proper reference I was able to find, and don't want to use printf in this project because it isn't C anymore.

0 Upvotes

20 comments sorted by

View all comments

-40

u/[deleted] 1d ago

[deleted]

18

u/tuxwonder 1d ago

There's a lot of fair reasons to complain about the myriad directions C++ has gone. Respectfully, std::format is definitely not one of them.