輸出流基本概念
輸出流定義在
使用輸出流的最簡單的方法是使用<<運算符。通過<<可以輸出C++的基本類型,例如int、指針、double和字符串。此外,C++的string類也兼容<<,C風格的字符串也能正常輸出。
int i = 7;
cout << i << endl;
char ch = 'a';
cout << ch << endl;
string str = "hello world !";
cout << str << endl;
C++流可以正確地解析C風格的轉義字符,例如包含\n的字符串,也可以使用std::endl開始一個新行。\n和endl的區別是,\n僅僅開始一個新行,而endl還會刷新緩存區。使用endl要小心,因為過多的刷新緩存區會降低性能。
輸出流的方法
put()和write()
put()和write()是原始的輸出方法。put()接受單個字符,write()接受一個字符數組。
flush()
向流寫入數據時,流不一定會將數據立即寫入目標。大部分輸出流都會進行緩存,也就是積累數據,而不是立即將得到的數據寫出去。當滿足一下條件之一是,流進行刷新操作(flush):
- 達到某個標記時,例如endl標記
- 流離開作用域被析構時。
- 要求從對應的輸入流輸入數據時(即要求從cin輸入時,cout會刷新)。
- 流緩存滿時。
顯示要求刷新緩存的方法是調用flush()方法。
cout << "abc";
cout.flush(); // abc is written to the console.
cout << "def";
cout.endl; // def is written to the console.
並不是所有的輸出流都會緩存,例如cerr流就不會緩存
處理輸出錯誤
- 當一個流處於正常的可用狀態時,稱這個流是好的。調用good()方法可以判斷這個流當前是否處於正常狀態。
- good()可以獲得流的基本驗證信息,但是不能提供流不可用的原因。bad()方法提供稍多的信息。如果bad()返回true,意味着發生了致命的錯誤。另一個方法fail()在最近一次操作失敗時返回true,但是沒有說明下一次操作是否也會失敗。
cout.flush();
if(cout.fail()){
cerr << "Unable to flush to standard out. " << endl;
}
- 通過clear()方法可以重置流的錯誤狀態
輸出操作算子
流的一項獨特性是,放入數據滑槽的內容並非僅限於數據,C++流還能識別操作算子,操作算子是能夠修改流行為的對象,而不是流能夠操作的數據。大部分的操作算子定義在
- boolalpha和noboolalpha:要求流將bool值輸出為true和false或1和0.
- hex、oct和dec:分別十六進制、八進制和十進制輸出數字。
- setprecision:設置輸出小數時小數位數。這是一個參數化的操作算子(也就是說這個操作算子接受一個參數)。
- setw:設置輸出數據的字段寬度。這是一個參數化操作算子。
- setfill:當數字寬度小數指定寬度時,設置用於填充的字符。
- showpoint和noshowpoint:對於不帶小數部分的浮點數,強制要求顯示或是不顯示小數點。
- put_money:向流寫入一個格式化的貨幣。
- put_time:向流寫入一個格式化的時間值。
- quoted:把給定的字符串封裝在引號中,並轉義嵌入引號。這個是一個參數化的操作算子。
// boolean values
bool myBool = true;
cout << "This is the default: " << myBool << endl;
cout << "This should be true: " << boolalpha << myBool << endl;
cout << "This should be 1: " << noboolalpha << myBool << endl;
// Money amount
cout << "This should be a money amount of 120000, formatted according to your location: "<< put_money("120000") << endl;
// Date and time
time_t t_t = time(nullptr); // Get current system time.
tm* t = localtime(&t_t); // Convert to local time.
cout << "This should be the current date and time formatted according to your location: " << put_time(t,"%c") << endl;
// C++14 : Quoted string
cout << "This should be \"Quoted string with \\\"embedded quotes\\\".\" :" << quoted("Quoted string with \" embedded quotes\".") << endl;