就可以圍繞標準輸出緩衝區中的另一包裝:
#include <iostream>
#include <iomanip>
int main() {
int x = 76;
std::ostream hexcout (std::cout.rdbuf());
hexcout << std::hex;
std::cout << x << "\n"; // still "76"
hexcout << x << "\n"; // "4c"
}
在func重刑:
void print(std::ostream& os) {
std::ostream copy (os.rdbuf());
copy << std::hex;
copy << 123;
}
當然,如果性能是一個問題,這是一個有點貴,因爲它是複製整個ios
對象(但不包括緩衝區)在內的一些東西,你付出的,但不太可能使用如語言環境。
否則我覺得如果你打算使用.flags()
,最好保持一致並使用.setf()
而不是<<
語法(風格的純粹問題)。
void print(std::ostream& os) {
std::ios::fmtflags os_flags (os.flags());
std::size_t os_width (os.width());
os.setf(std::ios::hex);
os.width(4);
os << 123;
os.flags(os_flags);
os.width(os_width);
}
正如其他人說你可以把上面的(和.precision()
和.fill()
,但通常沒有語言環境和單詞相關的東西,通常不會被修改,並且較重)一類爲方便和使其異常安全;構造函數應該接受std::ios&
。
我相信十六進制只能用於下一個移出操作。如果您手動更改格式標誌而不是使用操縱器,則更改僅保留。 – 2010-02-16 15:39:20
@BillyONeal:不,使用操縱器與手動更改格式標誌具有相同的效果。 :-P – 2010-02-16 15:55:45
如果您在此處由於Covertiy發現***不恢復ostream格式(STREAM_FORMAT_STATE)***,請參閱[Coverity finding:Not restoring ostream format(STREAM_FORMAT_STATE)](http://stackoverflow.com/ q/34503914)。 – jww 2016-01-25 21:11:29