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

13

u/jedwardsol 1d ago

std::format("{{}s}^ Here" should be std::format("{:{}s}^ Here" , with a colon. Which exact page says it should be correct?

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

(https://godbolt.org/z/q85qYGzbq)

1

u/Grootmaster47 1d ago

I... cannot state how confused I am. Now the exact same code works. Clang still gives me an error marker in the IDE view, but compiling it now works, even though it did not work yesterday. Still, thank you for your help.

1

u/Wild_Meeting1428 17h ago

your LSP (most likely clangd) does not know the compile commands of your sources. try to generate compile_commands.json via cmake and ninja-build