2012-11-24 25 views
0

我有一个程序,显示从文本文件中读入的歌曲以及时间,并以整洁的方式在控制台中显示它们。我遇到了麻烦,但是我的时间格式(00:00:00)有整数显示0106而不是16。我如何处理输出以显示整数零,当它低于10时?用整数在控制台中显示无意义的数字

从我的程序输出的一个例子:

SONG TITLE 
The once and future carpenter  0:4:52 
I never knew you     0:7:48 
Life        0:10:52 
February seven      0:15:0 
My lfe        0:24:12 
Yuor frei       0:37:20 
Lisjlf        0:49:23 
Lasifj        0:53:39 
Longsong       1:9:2 
Longer        1:22:3 
Almost done      1:34:48 

Process returned 0 (0x0) execution time : 0.280 s 
Press any key to continue. 

所需的输出:

SONG TITLE 
The once and future carpenter  00:04:52 
I never knew you     00:07:48 
Life        00:10:52 
February seven      00:15:00 
My lfe        00:24:12 
Yuor frei       00:37:20 
Lisjlf        00:49:23 
Lasifj        00:53:39 
Longsong       01:09:02 
Longer        01:22:03 
Almost done      01:34:48 

Process returned 0 (0x0) execution time : 0.280 s 
Press any key to continue. 

回答

1

你如何展示你的价值观?使用标准库提供的流工具?如果是这样,您可以使用setw操纵器与setfill一起使用。 stdio同行还允许指定widht和填充,使用适当的标志与格式说明:

#include <iomanip> 
#include <iostream> 

... 
cout << setw(2) << setfill('0') << h << ':' 
    << setw(2) << setfill('0') << m << ':' 
    << setw(2) << setfill('0') << s << '\n'; 
1
printf("%02d:%02d:%02\n", h, m, s); 
+0

我宁愿开始,经过C解决方案的C++的解决方案,但我会记住这一点。 –

+1

哦,C++? 'std :: printf(“%02d:%02d:%02 \ n”,h,m,s);'然后。 – melpomene

+0

我更喜欢所有解决方案,因为它是最简单的解决方案,也是最高效的解决方案。 – Blodyavenger