std::setw
來自 cppreference.com
定義於標頭檔案 <iomanip> |
||
/* 未指定 */ setw( int n ); |
||
當在表示式 out << std::setw(n) 或 in >> std::setw(n) 中使用時,它將流 out 或 in 的 width
引數設定為精確的 n。
某些操作會將寬度重置為零(參見下文),因此可能需要重複呼叫 std::setw
以設定多次操作的寬度。
目錄 |
[編輯] 引數
n | - | 寬度的新值 |
[編輯] 返回值
一個未指定型別的物件,使得
- 如果 out 是型別為 std::basic_ostream<CharT, Traits> 的物件,則表示式 out << setw(n)
- 的型別為 std::basic_ostream<CharT, Traits>&
- 值為 out
- 其行為如同呼叫了 f(out, n)
- 如果 in 是型別為 std::basic_istream<CharT, Traits> 的物件,則表示式 in >> setw(n)
- 的型別為 std::basic_istream<CharT, Traits>&
- 值為 in
- 其行為如同呼叫了 f(in, n)
其中函式 f 定義為
void f(std::ios_base& str, int n) { // set width str.width(n); }
[編輯] 注意
如果呼叫以下任何函式,流的寬度屬性將被重置為零(表示“未指定”):
- 輸入
- 輸出
- basic_ostream::operator<<() 的過載,它接受算術型別或 void 指標(在 num_put::put() 的第 3 階段)
- operator<<(basic_ostream&, char) 和 operator<<(basic_ostream&, char*)
- operator<<(basic_ostream&, basic_string&)
- std::put_money(在 money_put::put() 內部)
- std::quoted(與輸出流一起使用時)
此修飾符對輸入和輸出的具體影響因各個 I/O 函式而異,並在每個 operator<< 和 operator>> 過載頁面中單獨描述。
[編輯] 示例
執行此程式碼
#include <iomanip> #include <iostream> #include <sstream> int main() { std::cout << "no setw: [" << 42 << "]\n" << "setw(6): [" << std::setw(6) << 42 << "]\n" << "no setw, several elements: [" << 89 << 12 << 34 << "]\n" << "setw(6), several elements: [" << 89 << std::setw(6) << 12 << 34 << "]\n"; std::istringstream is("hello, world"); char arr[10]; is >> std::setw(6) >> arr; std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \"" << arr << "\"\n"; }
輸出
no setw: [42] setw(6): [ 42] no setw, several elements: [891234] setw(6), several elements: [89 1234] Input from "hello, world" with setw(6) gave "hello"
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 183 | C++98 | setw 只能與流一起使用型別 std::ostream 或 std::istream |
可用於任何 字元流 |
[編輯] 另請參閱
管理欄位寬度 ( std::ios_base 的公共成員函式) | |
更改填充字元 (函式模板) | |
設定填充字元的位置 (函式) | |
控制是否使用字首指示數字基數 (函式) |