cpp icon indicating copy to clipboard operation
cpp copied to clipboard

Strings exercise wrongly states that sprintf is preferred for string formatting

Open willeccles opened this issue 2 years ago • 3 comments

In C++, string formatting using sprintf is absolutely not the preferred way to do it, and is incompatible with std::string to boot. This should be corrected to recommend std::stringstream instead.

willeccles avatar Jun 09 '22 21:06 willeccles

Which exercise are talking about?

siebenschlaefer avatar Jun 09 '22 21:06 siebenschlaefer

https://github.com/exercism/cpp/blob/main/exercises/concept/strings/.docs/after.md

willeccles avatar Jun 09 '22 21:06 willeccles

I see. I think this is a first attempt at creating concepts and concept exercises.
I agree that std::ostringstream should be preferred in general.

siebenschlaefer avatar Jun 09 '22 21:06 siebenschlaefer

With C++ 20 we have the introduction of std::format which is more efficient and, in my opinion, more familiar and easier to use. As sprintf it also works with a formatting string and a variable set of arguments that are replaced in the formatting string.

raffaine avatar Dec 27 '22 20:12 raffaine

std::format support is brand new as of GCC 13 and Clang 15 (Clang 14 does not support it unless built with experimental features enabled). I still use {fmt} (and probably will for the foreseeable future), but I do think std::format is the correct solution here. It just may ostracize some users who do not have new enough STLs.

willeccles avatar Dec 27 '22 20:12 willeccles

Currently the C++ track uses C++17 because C++20 might not be available on some LTS Linux releases.
When we get to a point where we switch to C++20 and std::format is supported by the C++ compiler on those LTS releases I agree, we should recommend std::format. (Personally whenever I have the choice I'm happy with {fmt}.)

siebenschlaefer avatar Dec 27 '22 21:12 siebenschlaefer

@willeccles The string concept has been updated and can be seen on the main branch. It is not yet available on the website, but you can browse the files here on github to see if they have improved.

If you think there is something that should be added or changed, please open a new issue.

vaeng avatar Jun 27 '23 19:06 vaeng