Namespaces, I/O streams. Namespaces Namespace – what’s this? Namespace – what’s this?namespace When do we need the namespace? When do we need the namespace?

Slides:



Advertisements
Similar presentations
Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005.
Advertisements

IOStreams CNS 3370 Copyright 2003, Fresh Sources, Inc.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
 2006 Pearson Education, Inc. All rights reserved Stream Input/Output.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Unformatted and Formatted I/O Operations. 2 Unformatted Input/output is the most basic form of input/output. Unformatted I/O transfers the internal binary.
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
C++ Programming Certificate University of Washington Cliff Green
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 11 Customizing I/O Bjarne Stroustrup
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 12 - C++ Stream Input/Output Outline 12.1 Introduction 12.2 Streams Classic Streams vs.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ Streams Lecture-2.
Chapter 10C++ for Java Programmers1 Chapter 10 Input/Output.
File I/O ifstreams and ofstreams Sections 11.1 &
File I/O ifstreams and ofstreams. Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store.
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Student Book Input / Output in C++
1 I/O  C++ has no built-in support for input/output input/output is a library (iostream)  C++ program views input and output as a stream of bytes  Input:
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 31 Thanks for Lecture Slides: C How to Program by Paul Deital &
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
CS  Inserters and Extractors  Stream State  Files Streams  String Streams  Formatting  Manipulators  Internationalization.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 4 Working with Data Files.
CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
C++ How to Program, 8/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 13 Stream Input/Output C++ How to Program, 9/e © Copyright 2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
CS212: Object Oriented Analysis and Design
Chapter 8 CS 3370 – C++ I/O Classes.
Introduction to C++ (Extensions to C)
Basic Input and Output Operations
Chapter 21 - C++ Stream Input/Output
Friday, January 19, 2018 Announcements… For Today… For Next Time…
Standard Input/Output Streams
Standard Input/Output Streams
File I/O Streams, files, strings 1 1.
Lecture 5A File processing Richard Gesick.
Working with Data Files
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 13: Advanced File and I/O Operations
Topics Input and Output Streams More Detailed Error Testing
Chapter 12 - C++ Stream Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Programming with ANSI C ++
C++ Programming: chapter 6 – iostream
Chapter 12 - C++ Stream Input/Output
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
File I/O in C++ I.
Presentation transcript:

Namespaces, I/O streams

Namespaces Namespace – what’s this? Namespace – what’s this?namespace When do we need the namespace? When do we need the namespace?

Namespaces – using namespace mine { void printf(int); class file; void fprintf(const file &, int); } mine::printf(44); mine::file infile; fprintf(infile, );// if at least one function argument comes from // the „mine” namespace, then the function // fprintf() is looked for in this namespace first // (Koenig search rule)

Namespaces – using Namespaces may be extended/joined Namespaces may be extended/joined in a single source file in a single source file in many files in many files Any given name (or all the names) may be moved from namespace scope to the global (or local) scope Any given name (or all the names) may be moved from namespace scope to the global (or local) scope using mine::file; using mine::file; using namespace mine; using namespace mine; Avoid using „using” in the header files! Avoid using „using” in the header files! why? why? use the scope operator instead. use the scope operator instead.

Namespace std The C++ standard library is defined in the std namespace. The C++ standard library is defined in the std namespace. stream classes stream classes string classes string classes STL STL headers „with.h” and „without.h” headers „with.h” and „without.h” interesting fact: „*.hpp” and „*.hxx” are considered obsolete and non-standard interesting fact: „*.hpp” and „*.hxx” are considered obsolete and non-standard

Standard C++ I/O streams IOStream library (iostream) IOStream library (iostream) it’s the oldest part of the standard library it’s the oldest part of the standard library developed by AT&T developed by AT&T support for internationalization support for internationalization string types supported by library string types supported by library char * (compatibility with earlier routines) char * (compatibility with earlier routines) string string iostream is a library of templates, iostream is a library of templates, iostream uses exception mechanism iostream uses exception mechanism

IOStream library – basics classes classes input stream istream (from template: basic_istream ) input stream istream (from template: basic_istream ) output stream ostream (from template: basic_ostream ) output stream ostream (from template: basic_ostream )

IOStream library – basics objects (header file: ) objects (header file: ) istream cin; //stdin, buffered istream cin; //stdin, buffered ostream cout; //stdout, buffered ostream cout; //stdout, buffered ostream cerr; //stderr, not buffered ostream cerr; //stderr, not buffered //by default outputs to console ostream clog; //no C equivalent, buffered ostream clog; //no C equivalent, buffered //by default outputs to console //by default outputs to console

IOStream library – basics operators > operators > overloaded for fundamental types, including char *, void *, bool, overloaded for fundamental types, including char *, void *, bool, to be overloaded for classes requiring stream i/o to be overloaded for classes requiring stream i/o istream is; ostream os; int i; double d; os >i; os >d; os >i>>d; cout >i>>d; cout<< "\ni is " << i << " and d is " << d << " \n";

IOStream library – basics Manipulators Manipulators this are objects used to modify default behaviour of a stream (e.g. formatting), output „end of line” etc. this are objects used to modify default behaviour of a stream (e.g. formatting), output „end of line” etc. programmer may define his own operators programmer may define his own operators endl //outputs end of line and flushes the stream buffer cout<< "\ni is " << i << " and d is " << d << endl; ends// "\0"; ws// for istream stream read (and skip) white spaces flush dec, hex, oct

IOStream library – details ios_base basic_streambuf<> basic_streambuf<>basic_ios<> virtual virtual basic_istream<> basic_ostream<> basic_iostream<> basic_iostream<>

IOStream library – details ios_base common interface for stream classes independent on the class/type of the stream elements common interface for stream classes independent on the class/type of the stream elements current condition of the stream current condition of the stream formatting of the data being processed formatting of the data being processed

IOStream library – details basic_ios<> common interface for stream classes in extent dependent on the class/type of the stream elements common interface for stream classes in extent dependent on the class/type of the stream elements definition of the stream buffer (class derived from template basic_streambuf<> for specific class/type of the stream element, definitions of methods actually reading/writting data) definition of the stream buffer (class derived from template basic_streambuf<> for specific class/type of the stream element, definitions of methods actually reading/writting data)

IOStream library – details basic_istream<>basic_ostream<> templates for classes of read-only/write-only streams templates for classes of read-only/write-only streams they inherit virtually template basic_ios<> they inherit virtually template basic_ios<> for the char template argument they’re derived from istream i ostream respectively for the char template argument they’re derived from istream i ostream respectively headers: and headers: and

IOStream library – details basic_iostream<> templates of stream classes capable of reading and writting templates of stream classes capable of reading and writting header header

IOStream library – details result of stream operations result of stream operations status of the stream (within scope of ios_base, constants of type iostate) status of the stream (within scope of ios_base, constants of type iostate) goodbit// everything ok goodbit// everything ok // bits described below are zeroes // bits described below are zeroes eofbit// end of file reached eofbit// end of file reached failbit// last operation failed failbit// last operation failed // following operations will fail // following operations will fail // until failbit gets set to 0 // until failbit gets set to 0 badbit// failure; stream destroyed badbit// failure; stream destroyed

IOStream library – details result of stream operations - methods result of stream operations - methods bool good()// everything ok bool good()// everything ok bool eof() // end of file reached bool eof() // end of file reached bool fail() // last operation failed bool fail() // last operation failed bool bad() // failure; stream destroyed bool bad() // failure; stream destroyed rdstate()// read the stream state rdstate()// read the stream state clear()// set the state to goodbit clear()// set the state to goodbit clear(state)// set state to state clear(state)// set state to state setstate(state)//equivalent of setstate(state)//equivalent of // clear(rdstate() | state)

IOStream library – details result of stream operations – conversion operators result of stream operations – conversion operators operator void* ()// equivalent of !fail() operator void* ()// equivalent of !fail() if (cin>>x) // or: while(cin>>x) { // x read without an error } operator ! () // equivalent of fail() operator ! () // equivalent of fail() if ( !!(cin>>x)) // or: while( !!(cin>>x)) { // x read without an error }

IOStream library – details result of stream operations – exceptions result of stream operations – exceptions to define when to throw exceptions (method of stream class): to define when to throw exceptions (method of stream class):exceptions(flags) to check what may cause throwing exceptions (method of stream class): to check what may cause throwing exceptions (method of stream class):exceptions() if it returns goodbit, then exceptions are never thrown

IOStream library – details i/o – formatted and unformatted i/o – formatted and unformatted operators > by default do formatted i/o (specific precision, skipping white spaces etc.) operators > by default do formatted i/o (specific precision, skipping white spaces etc.) methods get*/put*/read*/write* etc. are for unformatted i/o only methods get*/put*/read*/write* etc. are for unformatted i/o only

IOStream library – details formatted i/o formatted i/o methods for format flags (ios::fmtflags) methods for format flags (ios::fmtflags) setf(flags);// set flags setf(flags);// set flags setiosflags(flags);// equivalent to setf(flags); setiosflags(flags);// equivalent to setf(flags); setf(flags, mask);// set flags within the mask group only setf(flags, mask);// set flags within the mask group only resetiosflags(mask);// equivalent to setiosflags(0, mask); resetiosflags(mask);// equivalent to setiosflags(0, mask); unsetf(flags);// clear flags unsetf(flags);// clear flags flags();// retrn flags currently set flags();// retrn flags currently set flags(flags);// set flags, clear all the remaining flags(flags);// set flags, clear all the remaining copyfmt(stream)// copy flags from stream copyfmt(stream)// copy flags from stream

IOStream library – details formatted i/o formatted i/o flags and masks flags and masks boolalpha// flag: type bool numeric (0/1) or descriptive boolalpha// flag: type bool numeric (0/1) or descriptive // true/false // true/false // there are also manipulators: boolalpha and noboolalpha adjustfield// mask: alignment (left, right, internal) adjustfield// mask: alignment (left, right, internal) left// flag: align to left left// flag: align to left right// flag: align to right right// flag: align to right internal// flag: for digits align sign to left internal// flag: for digits align sign to left // remaining characters to right // remaining characters to right // there are also manipulators: left, right and internal

IOStream library – details formatted i/o formatted i/o flags and masks flags and masks showpos// output „+” for positive numbers showpos// output „+” for positive numbers // there are also manipulators: showpos and noshowpos uppercase// print (upper case) hexadecimal digits uppercase// print (upper case) hexadecimal digits // there are also manipulators: uppercase and nouppercase basefield// mask: for bases of numerical system (see below) basefield// mask: for bases of numerical system (see below) dec, hex oct// flags for different numerical systems dec, hex oct// flags for different numerical systems (empty)// flag: output as dec, input according to (empty)// flag: output as dec, input according to // actual prefix 0x – hex, 0 – oct, else: dec // actual prefix 0x – hex, 0 – oct, else: dec // there are also manipulators: dec hex and oct

IOStream library – details formatted i/o formatted i/o flags and masks flags and masks showbase// precede numbers with prefix of numerical system showbase// precede numbers with prefix of numerical system // there are also manipulators: showbase and noshowbase floatfield// mask: format of the floating point floatfield// mask: format of the floating point fixed// decimal fraction (eg ) fixed// decimal fraction (eg ) scientific// use exponent (eg. 3.14e+0) scientific// use exponent (eg. 3.14e+0) (empty)// pick best one depending on value being oputput (empty)// pick best one depending on value being oputput // there are also manipulators: fixed and scientific showpoint// always output the dot ( ) showpoint// always output the dot ( ) // for the floating point // for the floating point // there are also manipulators: showpoint and noshowpoint

IOStream library – details formatted i/o formatted i/o precision()// return the precision precision()// return the precision // for the floating point, // by default 6 digits after dot precision(p)// return the precision precision(p)// return the precision // for the floating point // there is also manipulator: setprecision(w) // there is also manipulator: setprecision(w)

IOStream library – details formatted i/o formatted i/o flags flags skipws// skip white spaces skipws// skip white spaces // there are also manipulators: skipws and noskipws unitbuf// flush the output buffer unitbuf// flush the output buffer // after each << // after each << // there are also manipulators: unitbuf and nounitbuf

IOStream library – details formatted i/o formatted i/o width()// return width of the filed (number of characters) width()// return width of the filed (number of characters) // interpreted as: not less than // interpreted as: not less than width(w)// set the width of the filed (number of characters) width(w)// set the width of the filed (number of characters) // interpreted as: not less than // interpreted as: not less than // there is also manipulator: setw(w) char buf[80]; cin >> setw(sizeof(buffer)) >> buffer; fill() // return character that is used for filling the field fill() // return character that is used for filling the field fill(c) // set this character fill(c) // set this character // there is also manipulator: setfill(c)

IOStream library – details formatted i/o formatted i/o methods for internationalization, different character sets, etc. methods for internationalization, different character sets, etc. described in detail in the library reference ;-) described in detail in the library reference ;-)

IOStream library – details unformatted i/o unformatted i/o method get method get int get();// read one character, or EOF int get();// read one character, or EOF // equivalent to getchar()/getc() // equivalent to getchar()/getc() istream& get(char &c);// no EOF, instead test the stream state istream& get(char &c);// no EOF, instead test the stream state istream& get(char *pc, streamsize cnt) istream& get(char *pc, streamsize cnt) istream& get(char *pc, streamsize cnt, char delim) istream& get(char *pc, streamsize cnt, char delim) // read to pc buffer, stop after having read // read to pc buffer, stop after having read // cnt-1 characters, or after (just before) the delim character // cnt-1 characters, or after (just before) the delim character // do not input delim, append ‘\0’ // do not input delim, append ‘\0’ istream& ignore(streamsize cnt, char delim) istream& ignore(streamsize cnt, char delim) // couple variants, read, but do not store // couple variants, read, but do not store

IOStream library – details unformatted i/o unformatted i/o method getline method getline istream& getline(char *pc, streamsize cnt) istream& getline(char *pc, streamsize cnt) istream& getline(char *pc, streamsize cnt, char delim) istream& getline(char *pc, streamsize cnt, char delim) // read to pc buffer, stop after having read // cnt-1 characters, or after (just before) the delim // cnt-1 characters, or after (just before) the delim // or after reading end of line // delim is being read from the stream // if number of read characters is less than cnt // then set failbit state

IOStream library – details unformatted i/o unformatted i/o methods read and readsome – some aspects methods read and readsome – some aspects istream& read(char *pc, streamsize cnt) istream& read(char *pc, streamsize cnt) // read cnt characters // read cnt characters streamsize readsome(char *pc, streamsize cnt) streamsize readsome(char *pc, streamsize cnt) // return number of characters read, // return number of characters read, // read no more than cnt-1 characters // read no more than cnt-1 characters // input only the characters, that already are // input only the characters, that already are // in the input buffer (not destructive)

IOStream library – details unformatted i/o unformatted i/o int peek(char *pc, streamsize cnt) int peek(char *pc, streamsize cnt) // read next character, leave it in the buffer // read next character, leave it in the buffer istream& unget() istream& unget() // return to the stream one most recently read character // return to the stream one most recently read character // depending on the implementation, you may call it // depending on the implementation, you may call it // 1 or more times in a row // if it fails than set badbit istream& putback(char c) istream& putback(char c) // as above, but if c is not the most recently read character // as above, but if c is not the most recently read character // then set badbit

IOStream library – details unformatted i/o unformatted i/o ostream& put(char c) ostream& put(char c) // output c to the stream // output c to the stream ostream& write(const char *pc, streamsize cnt) ostream& write(const char *pc, streamsize cnt) // output cnt characters from pc to the stream // output cnt characters from pc to the stream // do not append the \0 // do not append the \0 ostream& flush() ostream& flush()

IOStream library – basics File stream classes File stream classes input stream ifstream (derived from template: basic_ifstream /derived from basic_istream /) input stream ifstream (derived from template: basic_ifstream /derived from basic_istream /) output stream ofstream (derived from template: basic_ofstream / derived from basic_ostream /) output stream ofstream (derived from template: basic_ofstream / derived from basic_ostream /) i/o stream fstream (derived from template: basic_fstream / derived from basic_iostream /) i/o stream fstream (derived from template: basic_fstream / derived from basic_iostream /)

IOStream library – basics int i; ifstream infile(„file.txt”); if (! infile) cout<<„file not opened”; cout<<„file not opened”;else infile >>i; infile >>i;

IOStream library – basics Flags for file streams (from the scope std::ios) Flags for file streams (from the scope std::ios) constructor arguments: fstream(name, flags=def) constructor arguments: fstream(name, flags=def) in// flag : input stream, default for ifstream in// flag : input stream, default for ifstream out// flag : output stream, default for ofstream out// flag : output stream, default for ofstream app// flag : for input stream, set the position to end of file app// flag : for input stream, set the position to end of file ate// flag : set the position to end of file ate// flag : set the position to end of file trunc// flag : remove the file contents (if not already empty) trunc// flag : remove the file contents (if not already empty) binary// flag : binary mode (do not interpret CR LF) binary// flag : binary mode (do not interpret CR LF) ifstream ibin(„data.bin”, std::ios::in | std::ios::binary);

IOStream library – basics Methods for file streams Methods for file streams open// ( file_name [, flags] ) open// ( file_name [, flags] ) close// () close// () is_open// is the file opened? is_open// is the file opened? tellg/tellp// get actual reading/writting(p) position (offset) tellg/tellp// get actual reading/writting(p) position (offset) seekg/seekp// seek for reading/writting seekg/seekp// seek for reading/writting // overloaded variants: relative/absolute position // overloaded variants: relative/absolute position ifstream ibin(„data.bin”, std::ios::in | std::ios::binary);

IOStream library – details Details on file stream classes Details on file stream classes described in detail in the library reference ;-) described in detail in the library reference ;-)

IOStream library – basics Classes for memory streams (string streams) Classes for memory streams (string streams) input stream istringstream (derived from template: basic_istringstream /derived from basic_istream /) input stream istringstream (derived from template: basic_istringstream /derived from basic_istream /) output stream ostringstream (derived from template: basic_ostringstream / derived from basic_ostream /) output stream ostringstream (derived from template: basic_ostringstream / derived from basic_ostream /) i/o stream stringstream (derived from template: basic_stringstream / derived from basic_iostream /) i/o stream stringstream (derived from template: basic_stringstream / derived from basic_iostream /)

IOStream library – details Details on memory stream classes Details on memory stream classes described in detail in the library reference ;-) described in detail in the library reference ;-)