2010-03-02 15 views
10

下面的小測試程序顯示出:如何使用機械手到我的十六進制輸出格式,用填充左零

和SS數爲= 3039

我想數量與填充打印出來左零,使總長度爲8,所以說:

和SS數爲= 00003039(注意額外的零左填充)

而且我想知道如何做到這一點通過操縱和字符串流作爲如下所示。謝謝!

測試程序:

#include <iostream> 
#include <sstream> 
#include <string> 
#include <vector> 

int main() 
{ 

    int i = 12345; 
    std::stringstream lTransport; 

    lTransport << "And SS Number IS =" << std::hex << i << '\n'; 

    std::cout << lTransport.str(); 

} 

回答

9

你看着圖書館的setfill和運輸及工務局局長操縱?

#include <iomanip> 
... 
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ; 
lTransport << std::setfill('0') << i << '\n'; 

我得到的輸出是:

And SS Number IS =00003039 
+0

如果我在格式化的h之前和之後添加東西例如,填充和寬度如何影響事物?有沒有辦法讓他們只應用於格式化的十六進制而不是整個串流? – bbazso 2010-03-02 19:39:44

+0

我編輯了我的答案以添加代碼。我希望它能爲你工作。哦!看起來像「Let_Me_Be」擊敗了我! – 2010-03-02 19:43:21

+0

設置格式化程序並寫入整數的stringstreamm後,可以根據需要重新調整setw()和setfill()。或者,您也可以使用sprintf(char_buf,'%08X',i)預格式化c字符串並將其寫入到字符串流中。 – 2010-03-02 19:48:22

2

我會用:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl; 
+0

難道你不能只說'std :: setw(8)'?畢竟,這是OP說他想要的東西。 – 2010-03-02 19:42:42

+0

@Kristo哦,是的,setw(8)會很好,我忽略了他總是想要8個角色。這將與位大小一致。 – 2010-03-02 19:49:21

1

您可以使用setwsetfill功能如下:

#include <iostream> 
#include <sstream> 
#include <string> 
#include <vector> 
#include <iomanip> 

using namespace std; 

int main() 
{  
    int i = 12345; 
    std::stringstream lTransport; 

    lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';  
    std::cout << lTransport.str(); // prints And SS Number IS =00003039  
}