2009-10-03 23 views
15

我有一行代碼將填充值設置爲我的輸出中的' - '字符,但需要將setfill標誌重置爲其默認空白字符。我怎麼做?如何重置輸出流操縱器標誌

cout << setw(14) << " CHARGE/ROOM" << endl; 
cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl; 

我想這可能工作:

cout.unsetf(ios::manipulatorname) // Howerver I dont see a manipulator called setfill 

上午我在錯誤的軌道上?

回答

9

您可以使用ios::fill()函數來設置和恢復填充字符。

http://www.cplusplus.com/reference/iostream/ios/fill/

#include <iostream> 
using namespace std; 

int main() { 
    char prev; 

    cout.width (10); 
    cout << 40 << endl; 

    prev = cout.fill ('x'); 
    cout.width (10); 
    cout << 40 << endl; 

    cout.fill(prev); 

    return 0; 
} 
26

看一看的Boost.IO_State_Savers,針對iostream的標誌提供RAII風格的範圍警衛。

例子:

#include <boost/io/ios_state.hpp> 

{ 
    boost::io::ios_all_saver guard(cout); // Saves current flags and format 

    cout << setw(14) << " CHARGE/ROOM" << endl; 
    cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl; 
// dtor of guard here restores flags and formats 
} 

更專業的警衛(僅用於填充或寬,或精度等......也都在庫中查看文檔的細節

+0

偉大的答案,應該是接受一個。 – gd1 2015-09-29 09:43:50

+3

@ gd1:很好的答案,但不是_great_,因爲我必須包含Boost才能保存iostream標誌。 – Isaac 2016-01-05 08:41:44

+1

@Isaac:在C++中,在我看來,您要麼使用boost或最終重新實現它,要麼等待Boost.Something被包含在標準中。 – gd1 2016-01-07 18:32:00

11

可以使用。 copyfmt保存COUT的初始格式。一旦與格式化輸出完成後,您可以再次使用它來恢復默認設置(包括填字)。

{ 
    // save default formatting 
    ios init(NULL); 
    init.copyfmt(cout); 

    // change formatting... 
    cout << setfill('-') << setw(11) << '-' << " "; 
    cout << setw(15) << '-' << " "; 
    cout << setw(11) << '-' << endl; 

    // restore default formatting 
    cout.copyfmt(init); 
} 
+0

驚訝的沒有人發佈過此文件:)將它滾動到RAII警衛將是很好,但如果發生異常。在日誌框架中遇到了這個問題。 – 2015-01-24 03:49:59

+0

這是在所有系統上工作嗎?當我嘗試它時,我的std :: cout在......之後拒絕輸出任何東西! – BitTickler 2015-01-26 06:59:32

1
// simply set it back 
float number = 4.5; 
cout << setfill('-'); 
cout << setw(11) << number << endl; // --------4.5 
cout << setfill(' '); 
cout << setw(11) << number << endl; // 4.5 
+2

將其設置爲'''',它可能是也可能不是它在第一個'setfill'之前的值。 – 2016-02-03 20:48:09

0

空字符將重置回它原來的狀態: setfill('\0')