[英]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.我刚开始在我的应用程序中使用
{fmt}
库,发现我无法使用该库来格式化具有不同位数的两个浮点数,因为程序崩溃了。
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).经过一些实验,我意识到它实际上有点糟糕,因为在我用
{0:.0f}
(或0:.2f
,就此而言)格式化任何浮点数后,我无法格式化任何东西。
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... 0:
是第一个, 1:
第二个……
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.您不能在相同格式的字符串中混合一些
{}
与参数计数器和其他没有这样的参数计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.