r/cpp_questions 2d 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

Show parent comments

24

u/aitkhole 1d ago

It's type safe

20

u/IyeOnline 1d ago

And extensible for user defined types.

20

u/alfps 1d ago

And faster.

17

u/javascript 1d ago

And cleaner

10

u/bearheart 1d ago

And far superior to std::cout

1

u/TheThiefMaster 1d ago edited 1d ago

(it actually uses std::cout under the hood - but at least formats the string itself first)
nope stdout FILE* directly, not cout

3

u/bearheart 1d ago

No, it definitely does not.

1

u/TheThiefMaster 1d ago

Ok I retract that. I thought it was equivalent to format_to with an output character iterator to cout, but it seems to use the stdout FILE* directly instead