НГТУ, каф. ВТ Потоки в С++ Макаревич Л. Г.. В языке Си++ нет особых операторов для ввода или вывода данных. Вместо этого имеется набор классов, стандартно.

Презентация:



Advertisements
Похожие презентации
Потоковые классы Потоки – последовательности байт, связанные с файлом либо с устройством ввода/вывода. Потоки по направлению обмена делятся на входные,
Advertisements

Unit II Constructor Cont… Destructor Default constructor.
1/27 Chapter 9: Template Functions And Template Classes.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1 A + B Операнд 1Операнд 2 Оператор Что такое выражение (expression) ? Что такое инструкция (statement) ? Операторы int max = (a > b) ? a : b;
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
Потоки Язык C++ не обеспечивает средств для ввода/вывода Ему это и не нужно; такие средства легко и элегантно можно создать с помощью самого языка Традиционно.
Форматирование Библиотека потоков С++ предусматривает три способа управления форматов выходных данных: вызов форматирующих функций-элементов использование.
Работа с файлами Сазонов Д.О. ПМиЭММ Часть 2. Тема занятия: Работа с файлами через потоки Для реализации файлового ввода/вывода, необходимо включить в.
Sequences Sequences are patterns. Each pattern or number in a sequence is called a term. The number at the start is called the first term. The term-to-term.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
© 2005 Cisco Systems, Inc. All rights reserved.INTRO v Constructing Network Addresses Calculating Subnet Masks.
Data Variable and Pointer Variable Pass by Reference Pointer Arithmetic Passing Array Using Pointers Dynamic Allocation.
Преобразование типов Макаревич Л. Г.. Операция приведения типов Тип ( выражение ) Тип ( выражение ) (тип) выражение (тип) выражение int a = 5; float b.
Standard I/O and Pipes. Standard Input and Output Linux provides three I/O channels to Programs Standard input (STDIN) - keyboard by default Standard.
Multiples Michael Marchenko. Definition In mathematics, a multiple is the product of any quantity and an integer. in other words, for the quantities a.
Exponential function. In mathematics, the exponential function is the function ex, where e is the number (approximately ) such that the function.
AVL-Trees COMP171 Fall AVL Trees / Slide 2 Balanced binary tree * The disadvantage of a binary search tree is that its height can be as large as.
Basic Input - Output. Output functions printf() – is a library function that displays information on-screen. The statement can display a simple text message.
Транксрипт:

НГТУ, каф. ВТ Потоки в С++ Макаревич Л. Г.

В языке Си++ нет особых операторов для ввода или вывода данных. Вместо этого имеется набор классов, стандартно поставляемых вместе с компилятором, которые и реализуют основные операции ввода-вывода. Библиотека классов для ввода-вывода решает две задачи. Во- первых, она обеспечивает эффективный ввод-вывод всех встроенных типов и простое, но тем не менее гибкое, определение операций ввода-вывода для новых типов, разрабатываемых программистом. Во-вторых, сама библиотека позволяет при необходимости развивать её и модифицировать.

Потоки iostream.h cout,cin и cerr cout - стандартный вывод, cin – стандартный ввод, cerr – стандартный поток сообщений об ошибках. cout и cerr выводят на терминал и принадлежат к классу ostream, cin имеет тип istream и вводит с терминала.

Вывод осуществляется с помощью операции >>, ввод с помощью операции

В классах iostream операции >> и для потоков class String { public: friend ostream& operator >(istream& is, String& s); private: char* str; int length; }; ostream& operator >(istream& is, String& s) { // предполагается, что строк длиной более // 1024 байтов не будет char tmp[1024]; is >> tmp; if s.str != 0) { delete []s.str; } s.length = strlen(tmp); s.str = new char[length + 1]; if (s.str == 0) { // обработка ошибок s.length = 0; return is; } strcpy(s.str, tmp); return is; } String x;... cin >> x; cout

Иерархия классов ввода-вывода cout, cerr, clog cin

#include class Date { int mo, da, yr; public: Date( int m, int d, int y ) { mo = m; da = d; yr = y; } friend ostream& operator > ( istream& is, Date& dt ) }; ostream& operator > ( istream& is, Date& dt ) { is >> dt.mo >> dt.da >> dt.yr; return is; } void main() { Date dt( 5, 6, 92 ); cout > dt; }

#include "stdafx.h" #include using namespace std; class Point { double x, y, z; public: Point(double a, double b, double c){x = a; y = b; z = c;} friend istream & operator >> ( istream & is, Point &c); friend ostream & operator > c; if ( isdigit(c)) { is.putback(c); return; } istream & operator >> ( istream & is, Point &p) { skipNotDigit(is); is >> p.x; skipNotDigit(is); is >> p.y; skipNotDigit(is); is >> p.z; return is; }; ostream & operator

Дополнительные функции istream istream& putback(char ch ); #include using namespace std; int main( ) { char c[10], c2, c3; c2 = cin.get( ); c3 = cin.get( ); cin.putback( c2 ); cin.getline( &c[0], 9 ); cout

#include class Complex { double re, im; public: Complex(double r, double i):re(r), im(i){} friend istream & operator >> ( istream & is, Complex &c); friend ostream & operator > ( istream & is, Complex &com) { double r, i; r = i = 0; char c = 0; is >> c; if ( c =='(') { is >> r>> c; if ( c==',') is >> i >> c; if ( c != ')') is.clear(ios::failbit); } else { is.putback(c); is >> r; } if ( is ) com = Complex(r, i); return is; }; ostream & operator

Форматирование функции-члены; флаги; манипуляторы

Функции-члены class ios inline int width() const; inline int width(int _i); inline ostream* tie(ostream* _os); // связан по умолчанию входной и выходной потоки // cin.tie(&cout); inline ostream* tie() const; inline char fill() const; inline char fill(char _c); inline int precision(int _i); inline int precision() const; #include int main() { char s[10]; cin.tie(0);//разрыв связи cout

Флаги enum { skipws = 0x0001, left = 0x0002, right = 0x0004, internal = 0x0008, dec = 0x0010, oct = 0x0020, hex = 0x0040, showbase = 0x0080, showpoint = 0x0100, uppercase = 0x0200, showpos = 0x0400, scientific = 0x0800, fixed = 0x1000, unitbuf = 0x2000, stdio = 0x4000 }; static const long basefield; // dec | oct | hex static const long adjustfield; // left | right | static const long floatfield; // scientific | fixed inline long flags() const; inline long flags(long _l); inline long setf(long _f,long _m); inline long setf(long _l); inline long unsetf(long _l); basefield Mask for obtaining the conversion base flags (dec, oct, or hex). adjustfield Mask for obtaining the field padding flags (left, right, or internal). floatfield Mask for obtaining the numeric format (scientific or fixed).

ios::skipws Skip white space on input. ios::left Left-align values; pad on the right with the fill character. ios::right Right-align values; pad on the left with the fill character (default alignment). ios::internal Add fill characters after any leading sign or base indication, but before the value. ios::dec Format numeric values as base 10 (decimal) (default radix). ios::oct Format numeric values as base 8 (octal). ios::hex Format numeric values as base 16 (hexadecimal). ios::showbase Display numeric constants in a format that can be read by the C++ compiler. ios::showpoint Show decimal point and trailing zeros for floating-point values. ios::uppercase Display uppercase A through F for hexadecimal values and E for scientific values. ios::showpos Show plus signs (+) for positive values. ios::scientific Display floating-point numbers in scientific format. ios::fixed Display floating-point numbers in fixed format. ios::unitbuf Cause ostream::osfx to flush the stream after each insertion. By default, cerr is unit buffered. ios::stdio Cause ostream::osfx to flush stdout and stderr after each insertion cout.setf(ios::scientific, ios::floatfield); cout.setf(ios::left, ios::adjustfield); cout.setf(ios::hex, ios::basefield);

Манипуляторы Манипуляторы – это объекты особых типов, которые управляют тем, как ostream или istream обрабатывают последующие аргументы. Некоторые манипуляторы могут также выводить или вводить специальные символы. endl при выводе перейти на новую строку; ends вывести нулевой байт (признак конца строки символов); flush немедленно вывести и опустошить все промежуточные буферы; dec выводить числа в десятичной системе (действует по умолчанию); oct выводить числа в восьмеричной системе; hex выводить числа в шестнадцатеричной системе счисления; setw (int n) установить ширину поля вывода в n символов ( n – целое число); setfill(int n) установить символ-заполнитель; этим символом выводимое значение будет дополняться до необходимой ширины; setprecision(int n) установить количество цифр после запятой при выводе вещественных чисел; resetiosflags( long lFlags ); Сбросить флаги ввода-вывода setiosflags( long lFlags); Установить флаги ввода.вывода setbase(int n) установить систему счисления для вывода чисел; n может принимать значения 0, 2, 8, 10, 16, причем 0 означает систему счисления по умолчанию, т.е. 10.

int x = 53; cout

Создание собственных манипуляторов без аргументов ostream& ostream::operator

Примеры #include void main() { double values[] = { 1.23, 35.36, 653.7, }; for( int i = 0; i < 4; i++ ) { cout.width(10); cout

#include #include void main() { double values[] = { 1.23, 35.36, 653.7, }; char *names[] = { "Zoot", "Jimmy", "Al", "Stan" }; for( int i = 0; i < 4; i++ ) cout

Выравнивание double values[ ] = { 1.23, 35.36, 653.7, }; char *names[ ] = { "Zoot", "Jimmy", "Al", "Stan" }; for ( int i = 0; i < 4; i++ ) cout

Точность double values[] = { 1.23, 35.36, 653.7, }; char *names[] = { "Zoot", "Jimmy", "Al", "Stan" }; for ( int i = 0; i < 4; i++ ) cout

Ввод-вывод файлов Класс ofstream (вывод) Класс ifstream (ввод) Оба они наследуют от класса fstream. Сами операции ввода- вывода выполняются так же, как и для других потоков – операции >> и

Вывод информации в файл ofstream(const char* szName, int nMode = ios::out, int nProt = filebuf::openprot); ios::app при записи данные добавляются в конец файла, даже если текущая позиция была перед этим перемещена; ios::ate при создании потока текущая позиция помещается в конец файла; однако, в отличие от режима app, запись ведется в текущую позицию; ios::in поток создается для ввода; если файл уже существует, он сохраняется; ios::out поток создается для вывода (режим по умолчанию); ios::trunc если файл уже существует, его прежнее содержимое уничтожается, и длина файла становится равной нулю; режим действует по умолчанию, если не заданы ios::ate, ios::app или ios::in ; ios::binary ввод-вывод будет происходить в двоичном виде, по умолчанию используется текстовое представление данных.

Можно создать поток вывода с помощью стандартного конструктора без аргументов, а позднее выполнить метод open с такими же аргументами, как у предыдущего конструктора: void open(const char* szName, int nMode = ios::out, int nProt = filebuf::openprot); Выводятся данные операцией

Двоичные файлы для вывода 1.Construct a stream as usual, then use the setmode member function, which changes the mode after the file is opened: ofstream ofs ( "test.dat" ); ofs.setmode( filebuf::binary ); ofs.write( char*iarray, 4 ); // Exactly 4 bytes writtensetmode 2.Specify binary output by using the ofstream constuctor mode argument: #include #include #include int iarray[2] = { 99, 10 }; void main() { ofstream os( "test.dat", ios::binary ); ofs.write( iarray, 4 ); // Exactly 4 bytes written }ofstream 3.Use the binary manipulator instead of the setmode member function: ofs

Ввод информации из файла Класс ifstream осуществляет ввод из файлов. При создании объекта типа ifstream в качестве аргумента конструктора можно задать имя существующего файла: ifstream(const char* szName, int nMode = ios::in, int nProt = filebuf::openprot); Можно воспользоваться стандартным конструктором, а подсоединиться к файлу с помощью метода open. Чтение из файла производится операцией >> или методами read или get: istream& read(char* pch, int nCount); istream& get(char& rch); Метод read вводит указанное количество байтов (nCount) в память, начиная с адреса pch. Метод get вводит один байт. Так же, как и для вывода, текущую позицию ввода можно изменить с помощью метода seekg Получить текущую позицию можно с помощью метода tellg() По завершении выполнения операций с файлами надо закрыть файлы с помощью close или просто уничтожить объект.

int get(); istream& get( char* pch, int nCount, char delim = '\n' ); istream& get( unsigned char* puch, int nCount, char delim = '\n' ); istream& get( signed char* psch, int nCount, char delim = '\n' ); istream& get( char& rch ); istream& get( unsigned char& ruch ); istream& get( signed char& rsch ); istream& get( streambuf& rsb, char delim = '\n' ); The unformatted get member function works like the >> operator. get function includes white-space characters, whereas the extractor excludes white space when the ios::skipws flag is set (the default). #include void main() { char line[25]; cout "; cin.get( line, 25 ); cout

istream& getline( char* pch, int nCount, char delim = '\n' ); istream& getline( unsigned char* puch, int nCount, char delim = '\n' ); istream& getline( signed char* psch, int nCount, char delim = '\n' ); nCount The maximum number of characters to store, including the terminating NULL, в отличие от get, которая не извлекает ограничитель istream& read( char* pch, int nCount ); istream& read( unsigned char* puch, int nCount ); istream& read( signed char* psch, int nCount ); #include void main() { char line[100]; cout

#include void main() { struct { double salary; char name[23]; } employee; ifstream is( "payroll", ios::binary | ios::nocreate ); if( is ) { // ios::operator void*() is.read( (char *) &employee, sizeof( employee ) ); cout

#include void main() { char ch; ifstream tfile( "payroll", ios::binary | ios::nocreate ); if( tfile ) { tfile.seekg( 8 ); // Seek 8 bytes in (past salary) while ( tfile.good() ) { // EOF or failure stops the reading tfile.get( ch ); if( !ch ) break; // quit on null cout

Обработка ошибок в потоках FunctionReturn value badReturns TRUE if there is an unrecoverable error. failReturns TRUE if there is an unrecoverable error or an expected condition, such as a conversion error, or if the file is not found. Processing can often resume after a call to clear with a zero argument. goodReturns TRUE if there is no error condition (unrecoverable or otherwise) and the end-of- file flag is not set. eofReturns TRUE on the end-of-file condition. clearSets the internal error state. If called with the default arguments, it clears all error bits. rdstateReturns the current error state. For a complete description of error bits, see the Class Library Reference. class ios

class ios {//… operator void *() const { if(state&(badbit|failbit) ) return 0; return (void *)this; } inline int ios::operator!() const { return state&(badbit|failbit); } inline int ios::bad() const { return state & badbit; } inline void ios::clear(int _i){ lock(); state = _i; unlock(); } inline int ios::eof() const { return state & eofbit; } inline int ios::fail() const { return state & (badbit | failbit); } inline int ios::good() const { return state == 0; }

The ! operator is overloaded to perform the same function as the fail function. Thus the expression if( !cout)... is equivalent to if( cout.fail() )... The void*() operator is overloaded to be the opposite of the ! operator; thus the expression if( cout)... is equal to if( !cout.fail() )... The void*() operator is not equivalent to good because it doesnt test for the end of file.

Копирование файлов #include "stdafx.h" #include using namespace std; void fchar(char * name_in, char * name_out) { ifstream in(name_in); ofstream out(name_out); char ch; if ( in && out) while ( in.get(ch)) out.put(ch); } void fline(char * name_in, char * name_out) { ifstream in(name_in); ofstream out(name_out); char buf[200]; while ( in && out) { in.getline(buf, sizeof(buf)); out

Строковые потоки Класс strstream #include void split_numbers(const char* s) { strstream iostr; iostr > x) cout

class istrstream : public istream class ostrstream : public ostream class strstream : public iostream

#include #include int main(int argc, char ** argv) { int id; float amount; char descr[41]; ifstream inf( argv[1]); if ( inf) { char inbuf[81]; int lineno = 0; cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); while( inf.getline(inbuf, 81)) { istrstream ins(inbuf, strlen(inbuf)); ins >> id >> amount >> ws; ins.getline(descr, 41); cout