如何填充printf以考虑负号和可变长度数?

Jon*_*age 27 c floating-point formatting printf

我试图在日志文件中输出一些数字,我想通过printf函数填充一大堆浮点数来产生:

 058.0
 020.0
 038.0
-050.0
 800.0
 150.0
 100.0
Run Code Online (Sandbox Code Playgroud)

目前我这样做:

printf("% 03.1f\n", myVar);
Run Code Online (Sandbox Code Playgroud)

...其中myVar是一个浮点数.该语句的输出如下所示:

58.0
20.0
38.0
-50.0
800.0
150.0
100.0
Run Code Online (Sandbox Code Playgroud)

根据我的阅读,我希望我的代码能够产生我在本文顶部提到的输出,但显然有些不对劲.你一次只能使用一面旗帜吗?..或者还有其他什么东西在这里?

Eri*_*rik 26

宽度说明符是完整的宽度:

printf("%05.1f\n", myVar);  // Total width 5, pad with 0, one digit after .
Run Code Online (Sandbox Code Playgroud)

要获得您期望的格式:

printf("% 06.1f\n", myVar);
Run Code Online (Sandbox Code Playgroud)