简体   繁体   中英

Cannot format two floating point numbers in one string using the {fmt} library

I am just starting to use the {fmt} library in my application, and found that I cannot use the library to format two floats with different number of digits, as the program crashes.

After some experimentation, I realized that it is actually a little bit worse, since I cannot format anything after I format any float with {0:.0f} (or 0:.2f , for that matter).

Example of code behaving counterintuitively to me:

#include <fmt\core.h>
#include <iostream>

int main()
{
    std::cout << fmt::format("{} , {}\n", 3.14, 10.0); // Prints out '3.14, 10.0'
    //std::cout << fmt::format("{0:.0f} , {}\n", 3.14, 10.0); // - ERROR: fmt::v6::format_error at memory location 
    std::cout << fmt::format("{0:.0f} , {0:.0f}\n", 3.14, 10.0); // - WRONG RESULT: Prints out '3, 3'
    std::cout << fmt::format("{0:.0f} , {:d}\n", 3.14, 10); // ERROR: fmt::v6::format_error at memory location

    //std::cout << fmt::format("{:s}, {:s}", fmt::format("{0:.2f}", 3.14), fmt::format("{:0:.1f}", 10.0)); // EVEN THIS DOESN'T WORK

    // This is the only way I found of getting the output I want:
    std::string a = fmt::format("{0:.2f}", 3.14);
    std::string b = fmt::format("{0:.1f}", 10.0);

    std::cout << fmt::format("{:s}, {:s}", a, b);

    return 0;
}

Numbers before : are used to count the arguments.
0: is the first, 1: the second...
If you don't put anything before : then the arguments will be considered in order.
You cannot mix in the same format string some {} with an argument counter and others without such an argument counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM