[英]How to cout middle zero with leading zero via one cout statement in C++?
我需要顯示從數據包二進制數據(0x123400005678)解析的三個值。
unsigned int k = 0x1234, l=0x0, m=0x5678;
當我使用cout三次時,可以顯示四位數的十六進制值。
#include <iostream>
#include <iomanip>
...
cout << "seperated cout" << endl;
cout << hex << setfill ('0') << setw (4) << k;
cout << hex << setfill ('0') << setw (4) << l;
cout << hex << setfill ('0') << setw (4) << m << endl;
....
seperated cout
123400005678
但是,當我只使用一條提示行時,省略了'0x0'的前導零...
#include <iostream>
#include <iomanip>
...
cout << "oneline cout" << endl;
cout << hex << setfill ('0') << setw (4) << k << l << m << endl;
...
oneline cout
123405678
無論如何,有一個行提示顯示類似“ 123400005678”嗎? 還是僅使用cout三次即可做到這一點?
先感謝您。
字段寬度不是“粘性”的,因此您需要為打印出的每個字段再次設置寬度:
cout << hex << setfill ('0') << setw (4) << k << setw(4) << l << setw(4) << m << endl;
結果:
123400005678
不過,填充字符是粘性的,因此通常您希望在使用其他設置的值后盡快將其設置回空格字符:
cout << setfill(' ');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.