Live data from Hacker News

Formatting text in C++: Old and new ways

mariusbancila.ro

1–10 of 73 posts

Re: Formatting text in C++: Old and new ways

#2

    unsigned char str[]{3,4,5,6,0};
    std::stringstream ss;
    ss 
> The content of text will be "str=♥♦♣♠".

no, it wont. if you are on an old Windows with code page 437 then sure. but on any sane UTF-8 system, you're just going to get some binary data.

1. https://wikipedia.org/wiki/Code_page_437

Re: Formatting text in C++: Old and new ways

#4
post #2

unsigned char str[]{3,4,5,6,0}; std::stringstream ss; ss > The content of text will be "str=♥♦♣♠". no, it wont. if you are on an old Windows with code page 437 then sure. but on any sane UTF-8 system, you're just going to get some binary data. 1. https://wikipedia.org/wiki/Code_page_437

Thanks for finding this out as a codepage issue. The implementation of the operator<< will indeed call ostream::widen() to expand character into a locale dependent equivalent.

Re: Formatting text in C++: Old and new ways

#7
Something else to consider is compile time versus runtime validation with formatting libraries, e.g. due to passing the wrong number or type of arguments. The Abseil str_format library does compile time validation for both when possible: https://abseil.io/docs/cpp/guides/format

Re: Formatting text in C++: Old and new ways

#9
I find it disappointing that cpp20 still doesn't have a solution that is more convenient than good ol printf (except for memory safety).

Another example would be convenient list comprehension, convenient maps wihout juggling around with tuples, first(), second(), at()...

Re: Formatting text in C++: Old and new ways

#10

I find it disappointing that cpp20 still doesn't have a solution that is more convenient than good ol printf (except for memory safety). Another example would be convenient list comprehension, convenient maps wihout juggling around with tuples, first(), second(), at()...

Maps have been improved quite a bit.

For example, if you have a std::map, you can iterate over it like this:

    for (auto [s, n]: my_map) {
        // s = string key, n = int value
    }
You can test for membership:

    if (my_map.contains(“foo”)) { /* do something * }
Although I still usually use find because if the key is in the map, I probably want the value.

You can use initialization lists with them too:

    std::map my_map = {
      { “one”, 1 },
      { “two”, 2 },
      { “three”, 3 }
    };
Post reply on HN