Класс ios_baseios_base Class
Этот класс описывает хранилище и функции-члены общие для обоих потоков (ввода и вывода), не зависящих от параметров шаблона.The class describes the storage and member functions common to both input and output streams that do not depend on the template parameters. (Шаблон класса basic_ios
описывает общие параметры и зависит от параметров шаблона.)(The class template basic_ios
describes what is common and is dependent on template parameters.)
Объект класса ios_base хранит сведения о форматировании, состоящие из следующих элементов:An object of class ios_base stores formatting information, which consists of:
Флаги формата в объекте типа
fmtflags
.Format flags in an object of typefmtflags
.Маска исключения в объекте типа
iostate
.An exception mask in an object of typeiostate
.Ширина поля в объекте типа
int
.A field width in an object of typeint
.Точность отображения в объекте типа
int
.A display precision in an object of typeint
.Объект языкового стандарта в объекте типа
locale
.A locale object in an object of typelocale
.Два расширяемых массива с элементами типа
long
иvoid
указателя.Two extensible arrays, with elements of typelong
andvoid
pointer.
Объект класса ios_base также хранит сведения о состоянии потока в объекте типа iostate
и стеке обратного вызова.An object of class ios_base also stores stream state information, in an object of type iostate
, and a callback stack.
ЧленыMembers
КонструкторыConstructors
ИмяName | ОписаниеDescription |
---|---|
ios_base |
Создает объект ios_base .Constructs ios_base objects. |
Определения типовTypedefs
ИмяName | ОписаниеDescription |
---|---|
event_callback |
Описывает функцию, переданную в register_call .Describes a function passed to register_call . |
fmtflags |
Константы для определения внешнего вида выходных данных.Constants to specify the appearance of output. |
iostate |
Определяет константы, описывающие состояние потока.Defines constants describing the state of a stream. |
openmode |
Описывает процесс взаимодействия с потоком.Describes how to interact with a stream. |
seekdir |
Задает начальную точку для операций смещения.Specifies starting point for offset operations. |
ПеречисленияEnums
ИмяName | ОписаниеDescription |
---|---|
event |
Задает типы событий.Specifies event types. |
КонстантыConstants
ИмяName | ОписаниеDescription |
---|---|
adjustfield |
Битовая маска, определенная как internal | left | right .A bitmask defined as internal | left | right . |
app |
Задает поиск до конца потока перед каждой вставкой.Specifies seeking to the end of a stream before each insertion. |
ate |
Задает поиск до конца потока при первом создании его управляющего объекта.Specifies seeking to the end of a stream when its controlling object is first created. |
badbit |
Регистрирует потерю целостности буфера потока.Records a loss of integrity of the stream buffer. |
basefield |
Битовая маска, определенная как dec | hex | oct .A bitmask defined as dec | hex | oct . |
beg |
Задает поиск относительно начала последовательности.Specifies seeking relative to the beginning of a sequence. |
binary |
Указывает, что файл должен быть считан как двоичный, а не текстовый поток.Specifies that a file should be read as a binary stream, rather than as a text stream. |
boolalpha |
Задает вставку или извлечение объектов типа bool в качестве имен (таких как true и false ), а не числовых значений.Specifies insertion or extraction of objects of type bool as names (such as true and false ) rather than as numeric values. |
cur |
Задает поиск относительно текущей позиции в последовательности.Specifies seeking relative to the current position within a sequence. |
dec |
Задает вставку или извлечение целочисленных значений в десятичном формате.Specifies insertion or extraction of integer values in decimal format. |
end |
Задает поиск относительно конца последовательности.Specifies seeking relative to the end of a sequence. |
eofbit |
Регистрирует конец файла при извлечении из потока.Records end-of-file while extracting from a stream. |
failbit |
Регистрирует сбой при извлечении допустимого поля из потока.Records a failure to extract a valid field from a stream. |
fixed |
Задает вставку значений с плавающей запятой в формате с фиксированной запятой (без поля экспоненты).Specifies insertion of floating-point values in fixed-point format (with no exponent field). |
floatfield |
Битовая маска, определенная как fixed | scientific A bitmask defined as fixed | scientific |
goodbit |
Очищает все биты состояния.All state bits clear. |
hex |
Задает вставку или извлечение целочисленных значений в шестнадцатеричном формате.Specifies insertion or extraction of integer values in hexadecimal format. |
in |
Задает извлечение из потока.Specifies extraction from a stream. |
internal |
Выполняет заполнение по ширине поля, вставляя символы заполнения в точке внутри созданного числового поля.Pads to a field width by inserting fill characters at a point internal to a generated numeric field. |
left |
Задает выравнивание по левому краю.Specifies left justification. |
oct |
Задает вставку или извлечение целочисленных значений в восьмеричном формате.Specifies insertion or extraction of integer values in octal format. |
out |
Задает вставку в поток.Specifies insertion to a stream. |
right |
Задает выравнивание по правому краю.Specifies right justification. |
scientific |
Задает вставку значений с плавающей запятой в экспоненциальном формате (с полем экспоненты).Specifies insertion of floating-point values in scientific format (with an exponent field). |
showbase |
Задает вставку префикса, отображающего базу созданного целочисленного поля.Specifies insertion of a prefix that reveals the base of a generated integer field. |
showpoint |
Задает безусловную вставку десятичной запятой в созданное поле с плавающей запятой.Specifies unconditional insertion of a decimal point in a generated floating-point field. |
showpos |
Задает вставку знака плюс в созданное неотрицательное числовое поле.Specifies insertion of a plus sign in a nonnegative generated numeric field. |
skipws |
Задает пропуск начальных пробелов перед определенными извлечениями.Specifies skipping leading white space before certain extractions. |
trunc |
Задает удаление содержимого существующего файла при создании его управляющего объекта.Specifies deleting contents of an existing file when its controlling object is created. |
unitbuf |
Обеспечивает запись выходных данных на диск после каждой вставки.Causes output to be flushed after each insertion. |
uppercase |
Задает вставку эквивалентных прописных букв для букв нижнего регистра в определенных вставках.Specifies insertion of uppercase equivalents of lowercase letters in certain insertions. |
ФункцииFunctions
ИмяName | ОписаниеDescription |
---|---|
failure |
Класс Member выступает в качестве базового класса для всех исключений, создаваемых функцией члена clear в шаблоне класса basic_ios.The member class serves as the base class for all exceptions thrown by the member function clear in class template basic_ios. |
flags |
Задает или возвращает текущие параметры флага.Sets or returns the current flag settings. |
getloc |
Возвращает сохраненный объект языкового стандарта.Returns the stored locale object. |
imbue |
Изменяет языковой стандарт.Changes the locale. |
Init |
Создает стандартные iostream объекты при создании.Creates the standard iostream objects when constructed. |
iword |
Присваивает значение, сохраняемое в виде iword .Assigns a value to be stored as an iword . |
precision |
Задает количество цифр для отображения числа с плавающей запятой.Specifies the number of digits to display in a floating-point number. |
pword |
Присваивает значение, сохраняемое в виде pword .Assigns a value to be stored as a pword . |
register_callback |
Задает функцию обратного вызова.Specifies a callback function. |
setf |
Задает указанные флаги.Sets the specified flags. |
sync_with_stdio |
Гарантирует, что iostream и операции с библиотекой времени выполнения C выполняются в том порядке, в котором они отображаются в исходном коде.Ensures that iostream and C run-time library operations occur in the order that they appear in source code. |
unsetf |
Отключает указанные флаги.Causes the specified flags to be off. |
width |
Задает длину потока вывода.Sets the length of the output stream. |
xalloc |
Указывает, что переменная должна быть частью потока.Specifies that a variable shall be part of the stream. |
ОператорыOperators
ИмяName | ОписаниеDescription |
---|---|
operator= |
Оператор присваивания для объектов ios_base .The assignment operator for ios_base objects. |
ТребованияRequirements
Заголовок:<ios>Header: <ios>
Пространство имен: stdNamespace: std
event
event
Задает типы событий.Specifies event types.
enum event {
erase_event,
imbue_event,
copyfmt_event};
RemarksRemarks
Тип является перечислимым типом, описывающим объект, который может хранить событие обратного вызова, используемое в качестве аргумента функции, зарегистрированной в register_callback
.The type is an enumerated type that describes an object that can store the callback event used as an argument to a function registered with register_callback
. Различные значения события:The distinct event values are:
copyfmt_event
, чтобы найти обратный вызов, который выполняется около конца вызова методаcopyfmt
, непосредственно перед копированием маски исключения .copyfmt_event
, to identify a callback that occurs near the end of a call tocopyfmt
, just before the exception mask is copied.erase_event
, чтобы найти обратный вызов, который выполняется в начале вызова методаcopyfmt
или в начале вызова деструктора для*this
.erase_event
, to identify a callback that occurs at the beginning of a call tocopyfmt
, or at the beginning of a call to the destructor for*this
.imbue_event
, чтобы найти обратный вызов, который выполняется в конце вызова методаimbue
, непосредственно перед возвратом функции.imbue_event
, to identify a callback that occurs at the end of a call toimbue
, just before the function returns.
ПримерExample
register_callback
Пример см. в разделе.See register_callback
for an example.
event_callback
event_callback
Описывает функцию, переданную в register_call
.Describes a function passed to register_call
.
typedef void (__cdecl *event_callback)(
event _E,
ios_base& _Base,
int _I);
ПараметрыParameters
_Base
Поток, в котором был вызов события.The stream in which the event was called.
_I
Определенное пользователем число.A user-defined number.
RemarksRemarks
Тип описывает указатель на функцию, которая может быть зарегистрирована в register_callback
.The type describes a pointer to a function that can be registered with register_callback
. Функции этого типа не должны вызывать исключение.This type of function must not throw an exception.
ПримерExample
См register_call
. пример, в котором используется event_callback
.See register_call
for an example that uses event_callback
.
failure
failure
Класс failure
определяет базовый класс для типов всех объектов, вызываемых как исключения, с помощью функций в библиотеке iostreams
, для отчетов об ошибках, обнаруженных во время операций буфера потока.The class failure
defines the base class for the types of all objects thrown as exceptions, by functions in the iostreams
library, to report errors detected during stream buffer operations.
namespace std {
class failure : public system_error {
public:
explicit failure(
const string& _Message,
const error_code& _Code = io_errc::stream);
explicit failure(
const char* str,
const error_code& _Code = io_errc::stream);
};
}
RemarksRemarks
Значение, возвращаемое what()
, — это копия _Message
, возможно, дополненная тестом на основе _Code
.The value returned by what()
is a copy of _Message
, possibly augmented with a test based on _Code
. Если значение _Code
не указано, значение по умолчанию — make_error_code(io_errc::stream)
.If _Code
is not specified, the default value is make_error_code(io_errc::stream)
.
ПримерExample
// ios_base_failure.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>
int main ( )
{
using namespace std;
fstream file;
file.exceptions(ios::failbit);
try
{
file.open( "rm.txt", ios_base::in );
// Opens nonexistent file for reading
}
catch( ios_base::failure f )
{
cout << "Caught an exception: " << f.what() << endl;
}
}
Caught an exception: ios_base::failbit set
flags
flags
Задает или возвращает текущие параметры флага.Sets or returns the current flag settings.
fmtflags flags() const;
fmtflags flags(fmtflags fmtfl);
ПараметрыParameters
fmtfl
Новое значение fmtflags
.The new fmtflags
setting.
Возвращаемое значениеReturn Value
Предыдущее или текущее значение fmtflags
.The previous or current fmtflags
setting.
RemarksRemarks
ios_base::fmtflags
Список флагов см. в разделе.See ios_base::fmtflags
for a list of the flags.
Первая функция-член возвращает сохраненные флажки формата.The first member function returns the stored format flags. Вторая функция – член сохраняет fmtfl
в флагах формата и возвращает свое предыдущее сохраненное значение.The second member function stores fmtfl
in the format flags and returns its previous stored value.
ПримерExample
// ios_base_flags.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>
int main ( )
{
using namespace std;
cout << cout.flags( ) << endl;
cout.flags( ios::dec | ios::boolalpha );
cout << cout.flags( );
}
513
16896
fmtflags
fmtflags
Константы для определения внешнего вида выходных данных.Constants to specify the appearance of output.
class ios_base {
public:
typedef implementation-defined-bitmask-type fmtflags;
static const fmtflags boolalpha;
static const fmtflags dec;
static const fmtflags fixed;
static const fmtflags hex;
static const fmtflags internal;
static const fmtflags left;
static const fmtflags oct;
static const fmtflags right;
static const fmtflags scientific;
static const fmtflags showbase;
static const fmtflags showpoint;
static const fmtflags showpos;
static const fmtflags skipws;
static const fmtflags unitbuf;
static const fmtflags uppercase;
static const fmtflags adjustfield;
static const fmtflags basefield;
static const fmtflags floatfield;
// ...
};
RemarksRemarks
Поддерживает манипуляторы в ios
.Supports the manipulators in ios
.
Тип — это тип битовой маски, описывающий объект, который может хранить флаги формата.The type is a bitmask type that describes an object that can store format flags. Ниже перечислены значения различных флагов (элементы).The distinct flag values (elements) are:
dec
, чтобы вставить или извлечь целочисленные значения в десятичном формате.dec
, to insert or extract integer values in decimal format.hex
, чтобы вставить или извлечь целочисленные значения в шестнадцатеричном формате.hex
, to insert or extract integer values in hexadecimal format.oct
, чтобы вставить или извлечь целочисленные значения в восьмеричном формате.oct
, to insert or extract integer values in octal format.showbase
, чтобы вставить префикс, отображающий базу созданного целочисленного поля.showbase
, to insert a prefix that reveals the base of a generated integer field.internal
, чтобы выполнить заполнение по ширине поля, вставляя символы заполнения в точке внутри созданного числового поля.internal
, to pad to a field width as needed by inserting fill characters at a point internal to a generated numeric field. (Сведения о задании ширины поля см. в разделеsetw
).(For information on setting the field width, seesetw
).left
, чтобы выполнить заполнение по ширине поля, вставляя символы заполнения в конец созданного числового поля (выравнивание по левому краю).left
, to pad to a field width as needed by inserting fill characters at the end of a generated field (left justification).right
, чтобы выполнить заполнение по ширине поля, вставляя символы заполнения в начало созданного числового поля (выравнивание по правому краю).right
, to pad to a field width as needed by inserting fill characters at the beginning of a generated field (right justification).boolalpha
, чтобы вставить или извлечь объекты типаbool
, например имена (такие какtrue
иfalse
), а не числовые значения.boolalpha
, to insert or extract objects of typebool
as names (such astrue
andfalse
) rather than as numeric values.fixed
, чтобы вставить значения с плавающей запятой в формате с фиксированной запятой (без поля экспоненты).fixed
, to insert floating-point values in fixed-point format (with no exponent field).scientific
, чтобы вставить значения с плавающей запятой в экспоненциальном формате (с полем экспоненты).scientific
, to insert floating-point values in scientific format (with an exponent field).showpoint
, чтобы выполнить безусловную вставку десятичной запятой в созданное поле с плавающей запятой.showpoint
, to insert a decimal point unconditionally in a generated floating-point field.showpos
, чтобы вставить знак плюс в созданное неотрицательное числовое поле.showpos
, to insert a plus sign in a nonnegative generated numeric field.skipws
, чтобы пропустить начальные пробелы перед определенными извлечениями.skipws
, to skip leading white space before certain extractions.unitbuf
, чтобы записывать выходные данные на диск после каждой вставки.unitbuf
, to flush output after each insertion.uppercase
, чтобы вставить эквивалентные прописные буквы для букв нижнего регистра в определенных вставках.uppercase
, to insert uppercase equivalents of lowercase letters in certain insertions.
Кроме того, ниже приведено несколько полезных значений:In addition, several useful values are:
adjustfield
, битовая маска, определенная какinternal
|left
|right
adjustfield
, a bitmask defined asinternal
|left
|right
basefield
, определенный какdec
|hex
|oct
basefield
, defined asdec
|hex
|oct
floatfield
, определенный какfixed
|scientific
floatfield
, defined asfixed
|scientific
Примеры функций, изменяющих эти флаги формата, см. в разделе <iomanip>
.For examples of functions that modify these format flags, see <iomanip>
.
getloc
getloc
Возвращает сохраненный объект языкового стандарта.Returns the stored locale object.
locale getloc() const;
Возвращаемое значениеReturn Value
Сохраненный объект языкового стандарта.The stored locale object.
ПримерExample
// ios_base_getlock.cpp
// compile with: /EHsc
#include <iostream>
int main( )
{
using namespace std;
cout << cout.getloc( ).name( ).c_str( ) << endl;
}
C
imbue
imbue
Изменяет языковой стандарт.Changes the locale.
locale imbue(const locale& _Loc);
ПараметрыParameters
_Loc
Новое значение языкового стандарта.The new locale setting.
Возвращаемое значениеReturn Value
Предыдущий языковой стандарт.The previous locale.
RemarksRemarks
Функция члена сохраняет _Loc
в объекте языкового стандарта, а затем сообщает о событии обратного вызова и imbue_event
.The member function stores _Loc
in the locale object and then reports the callback event and imbue_event
. Она возвращает предыдущее сохраненное значение.It returns the previous stored value.
ПримерExample
basic_ios::imbue
Пример см. в разделе.See basic_ios::imbue
for a sample.
Init
Init
Создает стандартные iostream
объекты при создании.Creates the standard iostream
objects when constructed.
class Init { };
RemarksRemarks
Вложенный класс описывает объект, построение которого гарантирует, что стандартные iostream
объекты должным образом созданы, даже перед выполнением конструктора для произвольного статического объекта.The nested class describes an object whose construction ensures that the standard iostream
objects are properly constructed, even before the execution of a constructor for an arbitrary static object.
ios_base
ios_base
Создает объекты ios_base.Constructs ios_base objects.
ios_base();
RemarksRemarks
(Защищенный) конструктор ничего не делает.The (protected) constructor does nothing. Последующий вызов basic_ios::
init должен инициализировать объект, прежде чем его можно будет безопасно уничтожить.A later call to basic_ios::
init must initialize the object before it can be safely destroyed. Таким образом, единственное безопасного использования класса ios_base является базовым классом для basic_iosшаблона класса.Thus, the only safe use for class ios_base is as a base class for class template basic_ios.
iostate
iostate
Тип констант, описывающих состояние потока.The type of constants that describe the state of a stream.
class ios_base {
public:
typedef implementation-defined-bitmask-type iostate;
static const iostate badbit;
static const iostate eofbit;
static const iostate failbit;
static const iostate goodbit;
// ...
};
RemarksRemarks
Тип — это тип битовой маски, описывающий объект, который может хранить данные о состоянии потока.The type is a bitmask type that describes an object that can store stream state information. Ниже перечислены значения различных флагов (элементы).The distinct flag values (elements) are:
badbit
регистрирует потерю целостности буфера потока.badbit
, to record a loss of integrity of the stream buffer.eofbit
регистрирует конец файла при извлечении из потока.eofbit
, to record end-of-file while extracting from a stream.failbit
регистрирует ошибку извлечения корректного поля из потока.failbit
, to record a failure to extract a valid field from a stream.
Кроме того, полезное значение — goodbit
, где ни один из ранее упомянутых битов не задан ( goodbit
гарантированно равен нулю).In addition, a useful value is goodbit
, where none of the previously mentioned bits are set (goodbit
is guaranteed to be zero).
iword
iword
Присваивает значение, сохраняемое в виде iword
.Assigns a value to be stored as an iword
.
long& iword(int idx);
ПараметрыParameters
idx
Индекс значения для сохранения как iword
.The index of the value to store as an iword
.
RemarksRemarks
Функция-член возвращает ссылку на элемент idx расширяемого массива с элементами типа long
.The member function returns a reference to element idx of the extensible array with elements of type long
. Все элементы эффективно присутствуют и изначально хранят нулевое значение.All elements are effectively present and initially store the value zero. Возвращенная ссылка является недопустимой после следующего вызова для iword
объекта, после того, как объект изменен вызовом метода basic_ios::
copyfmt
или после уничтожения объекта.The returned reference is invalid after the next call to iword
for the object, after the object is altered by a call to basic_ios::
copyfmt
, or after the object is destroyed.
Если idx
является отрицательным или если для элемента недоступно уникальное хранилище, функция вызывает setstate
(badbit)
и возвращает ссылку, которая может быть неуникальной.If idx
is negative or if unique storage is unavailable for the element, the function calls setstate
(badbit)
and returns a reference that might not be unique.
Чтобы получить уникальный индекс для использования во всех объектах типа ios_base
, вызовите xalloc
.To obtain a unique index, for use across all objects of type ios_base
, call xalloc
.
ПримерExample
xalloc
Пример использования см. в разделе iword
.See xalloc
for a sample of how to use iword
.
openmode
openmode
Описывает процесс взаимодействия с потоком.Describes how to interact with a stream.
class ios_base {
public:
typedef implementation-defined-bitmask-type openmode;
static const openmode in;
static const openmode out;
static const openmode ate;
static const openmode app;
static const openmode trunc;
static const openmode binary;
// ...
};
RemarksRemarks
Режим открытия для нескольких iostream
объектов.The opening mode for several iostream
objects. Значения флагов:The flag values are:
КонстантаConstant | ДействиеEffect |
---|---|
app |
Поиск в конце потока перед каждой записьюSeek to the end of the stream before each write |
ate |
Поиск в конце потока сразу после открытияSeek to the end of the stream immediately after open |
binary |
Открыть в двоичном режиме.Open in binary mode. ( fopen Описание двоичного режима см. в разделе).(See fopen for a description of binary mode.) |
in |
Открыть для чтенияOpen for reading |
out |
Открыть для записиOpen for writing |
trunc |
удалить содержимое файла после открытияdelete the contents of the file after open |
ПримерExample
// ios_base_openmode.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>
int main ( )
{
using namespace std;
fstream file;
file.open( "rm.txt", ios_base::out | ios_base::trunc );
file << "testing";
}
operator=
operator=
Оператор присваивания для объектов ios_base.The assignment operator for ios_base objects.
ios_base& operator=(const ios_base& right);
ПараметрыParameters
right
Объект типа ios_base
.An object of type ios_base
.
Возвращаемое значениеReturn Value
Объект, которому выполняется присваивание.The object being assigned to.
RemarksRemarks
Оператор копирует сохраненные сведения о форматировании, создавая новую копию для любых расширяемых массивов.The operator copies the stored formatting information, making a new copy of any extensible arrays. Затем оно возвращает значение *this
.It then returns *this
. Обратите внимание, что стек обратных вызовов не копируется.Note that the callback stack is not copied.
Этот оператор используется только классами, производными от ios_base
.This operator is only used by classes derived from ios_base
.
precision
precision
Задает количество цифр для отображения числа с плавающей запятой.Specifies the number of digits to display in a floating-point number.
streamsize precision() const;
streamsize precision(streamsize _Prec);
ПараметрыParameters
_Prec
Количество значащих цифр при отображении, или количество цифр после десятичной запятой в фиксированной нотации.The number of significant digits to display, or the number of digits after the decimal point in fixed notation.
Возвращаемое значениеReturn Value
Первая функция-член возвращает сохраненное количество цифр для отображения.The first member function returns the stored display precision. Вторая функция – член сохраняет _Prec в точности экрана и возвращает свое предыдущее сохраненное значение.The second member function stores _Prec in the display precision and returns its previous stored value.
RemarksRemarks
Числа с плавающей запятой отображаются в фиксированной нотации с помощью fixed.Floating-point numbers are displayed in fixed notation with fixed.
ПримерExample
// ios_base_precision.cpp
// compile with: /EHsc
#include <iostream>
int main( )
{
using namespace std;
float i = 31.31234F;
cout.precision( 3 );
cout << i << endl; // display three significant digits
cout << fixed << i << endl; // display three digits after decimal
// point
}
31.3
31.312
pword
pword
Присваивает значение, сохраняемое в виде pword
.Assigns a value to be stored as a pword
.
void *& pword(int index);
ПараметрыParameters
index
Индекс значения для сохранения как pword
.The index of the value to store as a pword
.
RemarksRemarks
Функция-член возвращает ссылку на индекс элемента расширяемого массива с элементами типа void
Pointer.The member function returns a reference to element index of the extensible array with elements of type void
pointer. Все элементы эффективно присутствуют и изначально хранят нулевой указатель.All elements are effectively present and initially store the null pointer. Возвращенная ссылка является недопустимой после следующего вызова для pword
объекта, после того, как объект изменен вызовом метода basic_ios::
copyfmt
или после уничтожения объекта.The returned reference is invalid after the next call to pword
for the object, after the object is altered by a call to basic_ios::
copyfmt
, or after the object is destroyed.
Если индекс является отрицательным или для элемента недоступно уникальное хранилище, функция вызывает setstate
(badbit)
и возвращает ссылку, которая может быть неуникальной.If index is negative, or if unique storage is unavailable for the element, the function calls setstate
(badbit)
and returns a reference that might not be unique.
Чтобы получить уникальный индекс для использования во всех объектах типа ios_base
, вызовите xalloc
.To obtain a unique index, for use across all objects of type ios_base
, call xalloc
.
ПримерExample
См. xalloc
с примером использования pword
.See xalloc
for an example of using pword
.
register_callback
register_callback
Задает функцию обратного вызова.Specifies a callback function.
void register_callback(
event_callback pfn, int idx);
ПараметрыParameters
pfn
Указатель на функцию обратного вызова.Pointer to the callback function.
idx
Определенное пользователем число.A user-defined number.
RemarksRemarks
Функция-член помещает пару в {pfn, idx}
сохраненный стек обратного вызовастека обратного вызова.The member function pushes the pair {pfn, idx}
onto the stored callback stack callback stack. Когда сообщается о событии обратного вызова EV , функции вызываются в обратном порядке в реестре по выражению (*pfn)(ev, *this, idx)
.When a callback event ev is reported, the functions are called, in reverse order of registry, by the expression (*pfn)(ev, *this, idx)
.
ПримерExample
// ios_base_register_callback.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>
using namespace std;
void callback1( ios_base::event e, ios_base& stream, int arg )
{
cout << "in callback1" << endl;
switch ( e )
{
case ios_base::erase_event:
cout << "an erase event" << endl;
break;
case ios_base::imbue_event:
cout << "an imbue event" << endl;
break;
case ios_base::copyfmt_event:
cout << "an copyfmt event" << endl;
break;
};
}
void callback2( ios_base::event e, ios_base& stream, int arg )
{
cout << "in callback2" << endl;
switch ( e )
{
case ios_base::erase_event:
cout << "an erase event" << endl;
break;
case ios_base::imbue_event:
cout << "an imbue event" << endl;
break;
case ios_base::copyfmt_event:
cout << "an copyfmt event" << endl;
break;
};
}
int main( )
{
// Make sure the imbue will not throw an exception
// assert( setlocale( LC_ALL, "german" )!=NULL );
cout.register_callback( callback1, 0 );
cin.register_callback( callback2, 0 );
try
{
// If no exception because the locale's not found,
// generate an imbue_event on callback1
cout.imbue(locale("german"));
}
catch(...)
{
cout << "exception" << endl;
}
// This will
// (1) erase_event on callback1
// (2) copyfmt_event on callback2
cout.copyfmt(cin);
// We get two erase events from callback2 at the end because
// both cin and cout have callback2 registered when cin and cout
// are destroyed at the end of program.
}
in callback1
an imbue event
in callback1
an erase event
in callback2
an copyfmt event
in callback2
an erase event
in callback2
an erase event
seekdir
seekdir
Задает начальную точку для операций смещения.Specifies starting point for offset operations.
namespace std {
class ios_base {
public:
typedef implementation-defined-enumerated-type seekdir;
static const seekdir beg;
static const seekdir cur;
static const seekdir end;
// ...
};
}
RemarksRemarks
Тип является перечислимым типом, описывающим объект, который может хранить режим поиска, используемый в качестве аргумента для функций-членов нескольких iostream
классов.The type is an enumerated type that describes an object that can store the seek mode used as an argument to the member functions of several iostream
classes. Ниже перечислены значения различных флагов.The distinct flag values are:
beg
, чтобы найти (изменить текущее положение чтения или записи) относительно начала последовательности (массива, потока или файла).beg
, to seek (alter the current read or write position) relative to the beginning of a sequence (array, stream, or file).cur
, чтобы выполнить поиск относительно текущей позицией в последовательности.cur
, to seek relative to the current position within a sequence.end
, чтобы выполнить поиск относительно конца последовательности.end
, to seek relative to the end of a sequence.
ПримерExample
// ios_base_seekdir.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>
int main ( )
{
using namespace std;
fstream file;
file.open( "rm.txt", ios_base::out | ios_base::trunc );
file << "testing";
file.seekp( 0, ios_base::beg );
file << "a";
file.seekp( 0, ios_base::end );
file << "a";
}
setf
setf
Задает указанные флаги.Sets the specified flags.
fmtflags setf(
fmtflags _Mask
);
fmtflags setf(
fmtflags _Mask,
fmtflags _Unset
);
ПараметрыParameters
_Mask
Флажки, которые нужно включить.The flags to turn on.
_Unset
Флаги, которые необходимо отключить.The flags to turn off.
Возвращаемое значениеReturn Value
Предыдущие флаги форматаThe previous format flags
RemarksRemarks
Первая функция-член фактически вызывает flags(_Mask | _Flags)
(устанавливает выбранные биты), а затем возвращает предыдущие флаги формата.The first member function effectively calls flags(_Mask | _Flags)
(set selected bits) and then returns the previous format flags. Вторая функция-член фактически вызывает flags(_Mask & fmtfl, flags & ~_Mask)
(заменяя выбранные биты в маске), а затем возвращает предыдущие флаги формата.The second member function effectively calls flags(_Mask & fmtfl, flags & ~_Mask)
(replace selected bits under a mask) and then returns the previous format flags.
ПримерExample
// ios_base_setf.cpp
// compile with: /EHsc
#include <iostream>
int main( )
{
using namespace std;
int i = 10;
cout << i << endl;
cout.unsetf( ios_base::dec );
cout.setf( ios_base::hex );
cout << i << endl;
cout.setf( ios_base::dec );
cout << i << endl;
cout.setf( ios_base::hex, ios_base::dec );
cout << i << endl;
}
sync_with_stdio
sync_with_stdio
Гарантирует, что iostream
и операции с библиотекой времени выполнения C выполняются в том порядке, в котором они отображаются в исходном коде.Ensures that iostream
and C run-time library operations occur in the order that they appear in source code.
static bool sync_with_stdio(
bool _Sync = true
);
ПараметрыParameters
_Sync
Синхронизированы ли все потоки с stdio
.Whether all streams are in sync with stdio
.
Возвращаемое значениеReturn Value
Предыдущий параметр для этой функции.Previous setting for this function.
RemarksRemarks
Статическая функция-член сохраняет stdio
флаг синхронизации, который изначально имеет значение true
.The static member function stores a stdio
sync flag, which is initially true
. Когда true
этот флаг обеспечивает правильную синхронизацию операций в одном файле между iostreams
функциями и теми, которые определены в стандартной библиотеке C++.When true
, this flag ensures that operations on the same file are properly synchronized between the iostreams
functions and those defined in the C++ Standard Library. В противном случае синхронизация может быть гарантирована или не гарантируется, но производительность может быть улучшена.Otherwise, synchronization may or may not be guaranteed, but performance may be improved. Функция сохраняет _Sync в stdio
флаге синхронизации и возвращает предыдущее сохраненное значение.The function stores _Sync in the stdio
sync flag and returns its previous stored value. Его можно вызвать надежно только перед выполнением любых операций со стандартными потоками.You can call it reliably only before performing any operations on the standard streams.
unsetf
unsetf
Отключает указанные флаги.Turns the specified flags off.
void unsetf(
fmtflags _Mask
);
ПараметрыParameters
_Mask
Флаги, которые необходимо отключить.The flags that you want to turn off.
RemarksRemarks
Функция-член фактически вызывает flags(~_Mask & flags)
(очищает выбранные биты).The member function effectively calls flags(~_Mask & flags)
(clear selected bits).
ПримерExample
ios_base::setf
Пример использования см. в разделе unsetf
.See ios_base::setf
for a sample of using unsetf
.
width
width
Задает длину потока вывода.Sets the length of the output stream.
streamsize width( ) const;
streamsize width(
streamsize _Wide
);
ПараметрыParameters
_Wide
Нужный размер выходного потока.The desired size of the output stream.
Возвращаемое значениеReturn Value
Текущее значение ширины.The current width setting.
RemarksRemarks
Первая функция – член возвращает ширину сохраненного поля.The first member function returns the stored field width. Вторая функция – член сохраняет _Wide
ширину поля и возвращает свое предыдущее сохраненное значение.The second member function stores _Wide
in the field width and returns its previous stored value.
ПримерExample
// ios_base_width.cpp
// compile with: /EHsc
#include <iostream>
int main( ) {
using namespace std;
cout.width( 20 );
cout << cout.width( ) << endl;
cout << cout.width( ) << endl;
}
20
0
xalloc
xalloc
Указывает, что переменная является частью потока.Specifies that a variable is part of the stream.
static int xalloc( );
Возвращаемое значениеReturn Value
Статическая функция-член возвращает сохраненное статическое значение, которое увеличивается при каждом вызове.The static member function returns a stored static value, which it increments on each call.
RemarksRemarks
Возвращаемое значение можно использовать как аргумент уникального индекса при вызове функций-членов iword
или pword
.You can use the return value as a unique index argument when calling the member functions iword
or pword
.
ПримерExample
// ios_base_xalloc.cpp
// compile with: /EHsc
// Lets you store user-defined information.
// iword, jword, xalloc
#include <iostream>
int main( )
{
using namespace std;
static const int i = ios_base::xalloc();
static const int j = ios_base::xalloc();
cout.iword( i ) = 11;
cin.iword( i ) = 13;
cin.pword( j ) = "testing";
cout << cout.iword( i ) << endl;
cout << cin.iword( i ) << endl;
cout << ( char * )cin.pword( j ) << endl;
}
11
13
testing
См. такжеSee also
Безопасность потоков в стандартной библиотеке C++Thread Safety in the C++ Standard Library
Программирование iostreamiostream Programming
Соглашения iostreamiostreams Conventions