Distributed Real-Time Control Systems. Lecture 16 C++ Libraries Templates
|
|
- Logan Mathews
- 5 years ago
- Views:
Transcription
1 Distributed Real-Time Control Systems Lecture 16 C++ Libraries Templates 1
2 C++ Libraries One of the greatest advantages of C++ is to facilitate code reuse. If code is well organized and documented into libraries, many programming problems can be addressed using already existing code. We are going to look into the following libraries: The C Standard Library: to invoke legacy C functions using a C++ syntax. The C++ Standard Library: classes, templates and functions for common and widely used operations, including strings, stream I/O and the STL (Standard Template Libraries) for data structures and associated algorithms. Boost: a third party libraries, compatible with the C++ standard libraries, with classes and functions for cross platform multi-threaded programming. 2
3 The C Standard Library This library is an adaptation of the common C library functions, that are encapsulated in the std:: namespace. The following headers are available: <cassert> <cctype> <cerrno> <cfenv> <cfloat> <cintypes> <ciso646> <climits> <clocale> <cmath> <csetjmp> <csignal> <cstdarg> <cstdbool> <cstddef> <cstdint> <cstdio> <cstdlib> <cstring> <ctgmath> <ctime> <cuchar> <cwchar> <cwctype> Example: Equivalent to #include <cstdio> #include <stdio.h>; 3
4 The C++ Standard Library Includes many useful functions and classes for dealing with: Streams and Input/Output: <ios>, <iosfwd>, <streambuf>, <istream>, <ostream> <fstream>, <iostream>, <sstream>, <iomanip> Strings: <string>, <regex> Containers: <array>, <bitset>, <deque>, <forward_list>, <list>, <map>, <queue>, <set>, <stack>, <unordered_map>, <unordered_set>, <vector> General: <algorithm>, <chrono>, <functional>, <iterator>, <memory>, <stdexcept>, <tuple>, <utility>, <random> Localization: <locale>, <codecvt> Numerics: <complex>, <numeric>, <valarray>, <random> Utility: <exception>, <new>, <typeinfo>, <limits> Multi-Threading: <thread>, <mutex>, <condition_variable>, <future>, <atomic> 4
5 Strings are objects that manage arrays of characters. Defined in standard library <string> Strings Expression string s string s {str string s {char* string s{str,i string s{str,i,l string s{num, c string s{char*,len string s {initlist String construction/initialization Effect Creates empty string s Copy constructor Initialized from literal c-string String with chars starting at position i String with at most l chars starting at index i String with numoccurences of char c Initialized by len characters of c-string String initialized by all chars in initlist #include <iostream> #include <string> int main() { string s0 { Hello ; // Hello string s1 = Hello World ; // Hello World string s2 { Hello World, 5; // Hello string s3 {s1, 6,1000; // World string s4 {s3; //copy ctor string s5 {5, H ; // HHHHH string s6 {{ m,{ e ; // me string s7, s8; cin >> s7; //from cin getline(cin, s8); //from cin 5
6 Strings Functions Some important member functions Expression Effect =, assign() assign a new value Expression max_size() Effect returns maximum potential length swap() +=, append() Append string push_back() insert() erase() pop_back() clear() resize() replace() empty() size(), length() Swap value between two strings Append character insert string or character at position erase part of the string, reducing its length erase the last character erase all contents, string becomes empty truncates or expands the string replaces characters returns whether the string is empty returns the number of characters capacity() reserve() shrink_to_fit() number off characters that can be held without reallocation reserves memory for a certain number of characters Shrink to current size [], at() access a character front(), back() substr() clear() data(), c_str() access first or last character returns a certain substring erase all contents, string becomes empty returns raw character array + concatenates strings copy() copies content to raw character array 6
7 Examples: String Appending string& operator+= ( const string& ); string& operator+= ( const char* ); string& operator+= ( char ); string& append ( const string& ); string& append ( const char* ); string& append ( const string&, size_t, size_t); string& append ( const char*, size_t ); string& append ( size_t, char ); #include <iostream> #include <string> int main () { string str; string str2="writing "; string str3="print 10 and then 5 more"; str += str2; str.append(str3,6,3); // 10 str.append("dots are cool",5); // dots str += "here: ; str.append(10,'.'); //... cout << str << endl; return 0; Output: Writing 10 dots here... and then 5 more... 7
8 String Comparison Functions int compare (const string&) const; int compare (const char*) const; int compare (size_t, size_t, const string&) const; int compare (size_t, size_t, const char*) const; int compare (size_t, size_t, const string&, size_t, size_t) const; int compare (size_t, size_t, const char*, size_t) const; Return: 0 if equal, positive if greater, negative if smaller. operator==(), operator!=(), operator<() operator<=(), operator>(), operator>=() #include <iostream> #include <string> int main () { string str1 ("green apple"); string str2 ("red apple"); if (str1.compare(str2)!= 0) cout << str1 << " is not " << str2 << "\n"; if (str1.compare(6, 5, "apple") == 0) cout << "still, " << str1 << " is an apple\n"; if (str2.compare(str2.size()-5, 5, "apple") == 0) cout << "and " << str2 << " is also an apple\n"; if (str1.compare(6,5,str2,4,5) == 0) cout << "therefore, both are apples\n"; return 0; output: green apple is not red apple still, green apple is an apple and red apple is also an apple therefore, both are apples 8
9 Streams and I/O A stream is an abstraction for a stream of data in which character sequences flow. Examples: console, keyboard, string, file, socket, serial port. <ios>, <iosfwd>, <streambuf>, <istream>, <ostream> - the base classes <fstream>, <iostream>, <sstream>, <iomanip> - the ones to include. 9
10 Special stream objects cout and cin cout : object of class ostream represents the standard output stream. It corresponds to the cstdio stream stdout. can write characters as formatted data using the stream insertion operator (std::ostream::operator<<) cin - object of class istream represents the standard input stream. corresponds to the cstdio stream stdin. can retrieve characters from cin using the stream extraction operator (std::istream::operator>>) #include <iostream> int main() { int i = 5; float f = 2.0; char a = b ; cout << "i = " << i <<, f = << f <<, a= << a << endl; #include <iostream> int main() { int i; float f; char ch; cin >> i >> f >> ch; 10
11 Formatted Output #include <iostream> int main () { //set new flags cout.flags ( ios::right ios::hex ios::showbase ); cout.width (10); cout << 100; Output: return 0; 0x64 #include <iostream> int main () { double f = ; cout.setf(0,ios::floatfield); // floatfield disabled. //fixed point for few digits, scientific otherwise cout.precision(5); cout << f << endl; cout.precision(10); cout << f << endl; cout.setf(ios::fixed, ios::floatfield); // floatfield enabled cout << f << endl; return 0; Output: ios:: flags boolalpha showbase effect when set read/write bool elements as alphabetic strings (true and false). write integral values preceded by their corresponding numeric base prefix. showpoint write floating-point values including always the decimal point. showpos write non-negative numerical values preceded by a plus sign (+). skipws skip leading whitespaces on certain input operations. unitbuf flush output after each inserting operation. write uppercase letters replacing lowercase letters in certain uppercase insertion operations. basefiekd dec read/write integral values using decimal base format. hex oct floatfield fixed read/write integral values using hexadecimal base format. read/write integral values using octal base format. write floating point values in fixed-point notation. scientific write floating-point values in scientific notation. adjustfield internal left right the output is padded to the field width by inserting fill characters at a specified internal point. the output is padded to the field width appending fill characters at the end. the output is padded to the field width by inserting fill characters at the beginning. 11
12 File I/O // Copy a file #include <fstream> int main () { char * buffer; long size; ifstream infile ("test.txt",ifstream::binary); ofstream outfile("new.txt",ofstream::binary); // get size of file infile.seekg(0,ifstream::end); size=infile.tellg(); infile.seekg(0); buffer = new char [size]; // allocate memory infile.read (buffer,size); //read infile outfile.write (buffer,size); // write to outfile delete[] buffer; // release memory outfile.close(); infile.close(); return 0; Flag ios::in ios::out ios::app ios::ate ios::trunc ios::binary Function Opens an input file. Use this as an open mode for an ofstream to prevent truncating an existing file. Opens an output file. When used for an ofstream without ios::app, ios::ate or ios::in, ios::trunc is implied. Opens an output file for appending only. Opens an existing file (either input or output) and seeks to the end. Truncates the old file if it already exists. Opens a file in binary mode. The default is text mode. 12
13 Overloading operator<< For easy object display, we would like to be able to do the following: Cube c1 {1.0,1.0; Cylinder c2 {3.0,2.1,0.9; cout << c1 << c2 << endl; The code would invoke the method operator<< of cout with references to c1 (a Cube&) and c2 (a Cylinder&). But cout does not have these method. We need to define them and declare as friends in Cube and Cylinder. class Cube : public Solid { friend ostream& operator<<(ostream& os, Cube &c); ostream& operator<< (ostream& os, Cube &c) { os << Cube with density << c._d << and side length << c._s << endl; return os; Must do the same for Cylinder! 13
14 Base class operator<< Better if we can use polymorphism and use a single operator for solid. This requires helper virtual functions to print the objects. // In solid.h class Solid { friend ostream& operator<< (ostream&, Solid &); virtual void Print(ostream &os) = 0; //helper ostream& operator<< (ostream& os, Solid &c) { Print(os); return os; // In cube.h void Cube::Print(ostream &os) { os << Cube with density << _d << and side length << _s << endl; // In cylinder.h void Cylinder::Print(ostream &os) { os << Cylinder with density << _d <<, radius << _r << and height _h << endl; //In main.cpp #include "cube.h" #include "cylinder.h" #include <iostream> main() { Cylinder c1 {1.0,2.0,3.0; Cube *c2 = new Cube {2.0,0.9; cout << c1 << endl; cout << *c2 << endl; Output: Cylinder with density 1.0, radius 2.0 and height 3.0 Cube with density 2.0 and side length
15 The non-member operator ostream<< We have just extended the C++ language! We added another operator<<() to the already existing ones. // Built in ostream& operator<< (ostream& os, int &); ostream& operator<< (ostream& os, float &); ostream& operator<< (ostream& os, double &); ostream& operator<< (ostream& os, char &); ostream& operator<< (ostream& os, long &); // User defined ostream& operator<< (ostream& os, Solid &c); 15
16 Templates Templates are functions or classes with parametrized types. Function Template template <class T> T GetMax (T a, T b) { return ( a > b? a : b ); Class Template template <class T> class MyPair { T values [2]; public: MyPair (T first, T second) { values[0]=first; values[1]=second; ; //Invocation int x,y; GetMax <int> (x,y); //or GetMax(x,y); //Invocation MyPair <int> myints (115, 36); mypair <double> myfloats (3.0, 2.18); 16
17 More About Templates A template can have more than one argument. We can dynamicallyspecify the size of data structures. Templates can have default types. Template code iscompiled on demand. Should be defined in header files. //MULTIPLE ARGUMENTS template <class K, class T> void func(k a, T b); //invoke as func <int, float>(3, 4.0) //MIX TYPE AND VALUE ARGUMENTS template <class T, int size> class Pilha {T _dados[size];; //invoke as Pilha <int,128> p; //DEFAULT ARGUMENTS template <class T=char, int N=10> class mysequence {..; //can be invoked as mysequence<> myseq; //same as mysequence<char, 10> myseq; 17
18 Smart Pointers Raw pointers are dangerous: They may hold invalid memory addresses. It is hard to manage their release. In header <memory>, are defined smart pointer object to manage the lifetime of objects in a more structured way: unique_ptr represents exclusive ownership, cannot be copied. shared_ptr represents shared ownership, has reference count. weak_ptr to break loops in circular shared structures (advanced use). 18
19 unique_ptr A unique_ptr stores a pointer and deletes the associated object when itself is destroyed. One can use scopes to manage the object s lifetime. A unique_ptr cannot be copied The contained pointer is not directly accessible to users. Can be used as a pointer via the * and -> operators. Up-casting works as usual. #include <memory> #include cube.h double f1(unique_ptr<solid> up) { return up->calcmass(); double f2(unique_ptr<solid> & up) { return up->calcmass(); int main() { //... { //scope to manage new Cube s lifetime unique_ptr<cube> upc{new Cube {1.0,2.0 ; cout << f1(upc) << endl; //error, no copies cout << f2(upc) << endl; //ok, ref is passed // the Cube dies here //... 19
20 shared_ptr Used when two pieces of code need to access some data, but none is responsible for its destruction. Reference counting: it has a counter of how many copies exist. When the last copy is destroyed, the pointer is deleted. #include <memory> #include cube.h double f1(shared_ptr<solid> p) { //p is a local copy increments ref count return p->calcmass(); //p destroyed decrements ref count int main() { //... { shared_ptr<cube>spc {new Cube{1.0,2.0 ; // or alternative form // auto spc = make_shared<cube>(1,2); cout << f1(spc) << endl; //ok, value copy //spc destroyed decrements ref count //if ref count is 0, deletes object 20
21 Containers A container holds a sequence of objects. Sequence containers provide access to sequences of elements. vector, list, forward_list, deque Container adaptors provide specialized access to underlying containers. queue, priority_queue, stack Associative containers provide associative lookup. Ordered (implemented as balanced binary trees: map, multimap, set, multiset Unordered (implemented as hash tables): unordered_map, unordered_multimap, unordered_set, unordered_multiset 21
22 vector The vector is the STL default container. Use it unless you have a good reason not so. A vector holds a pointer to an array of elements, the number of elements, and the capacity. The elements of a vector are contiguously allocated in memory. A vector may grow if space for new elements exceeds capacity. Involves reallocation, that invalidates existing pointers to elements. #include <iostream> //need std::cout #include <memory> //need std::unique_ptr #include <vector> //need std::vector #include "cube.h #include "cylinder.h constexpr int max_elems {10; int main() { using T = unique_ptr<solid>; //type alias vector < T > sv; sv.reserve(max_elems); sv.push_back( T {new Cube {1.25,1.0 ); // same as sv[0] = T new Cube{1.25,1.0; sv.push_back( T {new Cylinder {1.0,0.4,0.9 ); cout << sv[0] << endl; //ok cout << sv[1] << endl; //ok //cout << sv[2] << endl; //runtime error //sv goes out of scope, all objects released 22
23 Iterators Iterators are pointers to elements of the container, that allow traversing it forward or backwards. Traversing a vector with iterators float TotalMass(vector<unique_ptr<Solid>> &v) { float mass {0.0; for(auto p = v.cbegin(); p!= v.cend(); p++) mass += (*p)->calcmass(); return mass; range-for: implicit use of begin() and end() float TotalMass(vector<unique_ptr<Solid>> &v) { float mass {0.0; for(auto &s : v) mass += s->calcmass(); return mass; 23
24 Algorithms Algorithms are functions that operate in a range of objects in a container. Ranges are specified by iterators, so algorithms can run on any container. Algorithms in <algorithm> for_each, find, find_if, find_end, find_first_of, adjacent_find, count, count_if, equal, mismatch, search, search_n. transform, copy, copy_backward, swap, swap_ranges, iter_swap, replace, replace_if, replace_copy, replace_copy_if, fill, fill_n, generate, generate_n, remove, remove_if, remove_copy, remove_copy_if, unique, unique_copy, reverse, reverse_copy, rotate, rotate_copy, random_shuffle, partition, stable_partition. sort, stable_sort, partial_sort, partial_sort_copy, nth_element. lower_bound, upper_bound, equal_range, binary_search merge, inplace_merge, includes, set_union, set_intersection, set_difference, set_symmetric_difference push_heap, pop_heap, make_heap, sort_heap min, max, min_element, max_element lexicographical_compare, next_permutation, prev_permutation 24
25 Example: The Sort Algorithm template <class RandomAccessIterator> void sort ( RandomAccessIterator first, RandomAccessIterator last ); template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp ); #include <iostream> #include <algorithm> #include <vector> bool myfunction (int i,int j) { return (i<j); struct myclass { bool operator() (int i,int j) { return (i<j); myobject; int main () { int myints[] = {32,71,12,45,26,80,53,33; vector<int> myvector (myints, myints+8); // sort (myvector.begin(), myvector.begin()+4); //( ) sort (myvector.begin()+4, myvector.end(), myfunction); // ( ) sort (myvector.begin(), myvector.end(), myobject); //( ) cout << "myvector contains:"; for (auto it=myvector.begin(); it!=myvector.end(); ++it) cout << " " << *it; cout << endl; return 0; 25
Major Language Changes, pt. 1
C++0x What is C++0x? Updated version of C++ language. Addresses unresolved problems in C++03. Almost completely backwards compatible. Greatly increases expressiveness (and complexity!) of language. Greatly
More informationTo use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8).
CHAPTER 23 STL Algorithms Objectives To use various types of iterators with the STL algorithms ( 23.1 23.20). To discover the four types of STL algorithms: nonmodifying algorithms, modifying algorithms,
More informationLecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.
Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard
More informationC++ Standard Template Library
C++ Standard Template Library CS 247: Software Engineering Principles Generic Algorithms A collection of useful, typesafe, generic (i.e., type-parameterized) containers that - know (almost) nothing about
More informationContents. 2 Introduction to C++ Programming,
cppfp2_toc.fm Page vii Thursday, February 14, 2013 9:33 AM Chapter 24 and Appendices F K are PDF documents posted online at www.informit.com/title/9780133439854 Preface xix 1 Introduction 1 1.1 Introduction
More informationDeitel Series Page How To Program Series
Deitel Series Page How To Program Series Android How to Program C How to Program, 7/E C++ How to Program, 9/E C++ How to Program, Late Objects Version, 7/E Java How to Program, 9/E Java How to Program,
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationStreams - Object input and output in C++
Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input
More informationC++ How To Program 10 th Edition. Table of Contents
C++ How To Program 10 th Edition Table of Contents Preface xxiii Before You Begin xxxix 1 Introduction to Computers and C++ 1 1.1 Introduction 1.2 Computers and the Internet in Industry and Research 1.3
More informationObjects and streams and files CS427: Elements of Software Engineering
Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...
More informationNew Iterator Concepts
New Iterator Concepts Author: David Abrahams, Jeremy Siek, Thomas Witt Contact: dave@boost-consulting.com, jsiek@osl.iu.edu, witt@styleadvisor.com Organization: Boost Consulting, Indiana University Open
More informationChapters and Appendices F J are PDF documents posted online at the book s Companion Website, which is accessible from.
Contents Chapters 23 26 and Appendices F J are PDF documents posted online at the book s Companion Website, which is accessible from http://www.pearsonhighered.com/deitel See the inside front cover for
More informationBoost.Compute. A C++ library for GPU computing. Kyle Lutz
Boost.Compute A C++ library for GPU computing Kyle Lutz GPUs (NVIDIA, AMD, Intel) Multi-core CPUs (Intel, AMD) STL for Parallel Devices Accelerators (Xeon Phi, Adapteva Epiphany) FPGAs (Altera, Xilinx)
More informationC++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions
Areas for Discussion C++ Functions Joseph Spring School of Computer Science Operating Systems and Computer Networks Lecture Functions 1 Last Week Introduction to Functions Program Structure and Functions
More informationC++ Programming Lecture 10 File Processing
C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential
More informationCS2141 Software Development using C/C++ Stream I/O
CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make
More informationParallelism and Concurrency in C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting
Parallelism and Concurrency in C++17 and C++20 Rainer Grimm Training, Coaching and, Technology Consulting www.grimm-jaud.de Multithreading and Parallelism in C++ Multithreading in C++17 Parallel STL The
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationCS11 Advanced C++ Lecture 2 Fall
CS11 Advanced C++ Lecture 2 Fall 2006-2007 Today s Topics C++ strings Access Searching Manipulation Converting back to C-style strings C++ streams Error handling Reading unformatted character data Simple
More informationUEE1303(1070) S 12 Object-Oriented Programming in C++
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member
More informationC++ Input/Output: Streams
C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:
More informationFig: iostream class hierarchy
Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationConvenient way to deal large quantities of data. Store data permanently (until file is deleted).
FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we
More informationComputational Physics
Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep
More informationConcepts for the C++0x Standard Library: Introduction
Concepts for the C++0x Standard Library: Introduction Douglas Gregor, Jeremiah Willcock, and Andrew Lumsdaine Open Systems Laboratory Indiana University Bloomington, IN 47405 {dgregor, jewillco, lums}@cs.indiana.edu
More informationEngineering Problem Solving with C++, Etter/Ingber
Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input
More informationModule 11 The C++ I/O System
Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationObject Oriented Programming Using C++ UNIT-3 I/O Streams
File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.
More informationPhysics 6720 I/O Methods October 30, C++ and Unix I/O Streams
Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard
More informationLecture 3 The character, string data Types Files
Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',
More informationCS11 Introduction to C++ Spring Lecture 8
CS11 Introduction to C++ Spring 2013-2014 Lecture 8 Local Variables string getusername() { string user; } cout user; return user;! What happens to user when function
More informationC and C++ Courses. C Language
C Language The "C" Language is currently one of the most widely used programming languages. Designed as a tool for creating operating systems (with its help the first Unix systems were constructed) it
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on
More informationAdvanced C++ STL. Tony Wong
Tony Wong 2017-03-25 C++ Standard Template Library Algorithms Sorting Searching... Data structures Dynamically-sized array Queues... The implementation is abstracted away from the users The implementation
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationThis chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.
C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++
More informationG52CPP C++ Programming Lecture 18
G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know
More informationChapter 14 Sequential Access Files
Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file
More informationI/O Streams and Standard I/O Devices (cont d.)
Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined
More informationCHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object
CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationUnit-V File operations
Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the
More informationWorking Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1
Document Number: N3960 Date: 2014-02-28 Reply to: Jared Hoberock NVIDIA Corporation jhoberock@nvidia.com Working Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1 Note: this
More informationECE 2400 Computer Systems Programming Fall 2017 Topic 12: Transition from C to C++
ECE 2400 Computer Systems Programming Fall 2017 Topic 12: Transition from C to C++ School of Electrical and Computer Engineering Cornell University revision: 2017-10-23-01-13 1 C++ Namespaces 2 2 C++ Functions
More informationInput and Output. Data Processing Course, I. Hrivnacova, IPN Orsay
Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course
More informationFile I/O Christian Schumacher, Info1 D-MAVT 2013
File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential
More informationPiyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class
C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams
More informationDistributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III
Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according
More informationObject Oriented Programming In C++
C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.
More informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More informationC++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield
C++ Programming Classes Michael Griffiths Corporate Information and Computing Services The University of Sheffield Email m.griffiths@sheffield.ac.uk Presentation Outline Differences between C and C++ Object
More informationChapter 3 - Notes Input/Output
Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:
More informationInput and Output File (Files and Stream )
Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14 Scope Describe the fundamentals of input & output files. Use data files for input & output purposes. Files Normally,
More informationG52CPP C++ Programming Lecture 18. Dr Jason Atkin
G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that
More informationStreams in C++ Stream concept. Reference information. Stream type declarations
Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read
More informationBen Van Vliet Ben Van Vliet March 3,
101101000101101001011101100110101010111010001010010101011011110011000110001010100101000000010 100010100100100110101101101000101101001011101100110101010111010001010010101011011110011000110 001010100101000000010100010100100100110101101101000101101001011101100110101010111010001010010
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationI BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.
Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'
More informationLecture 9. Introduction
Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of
More informationby Pearson Education, Inc. All Rights Reserved. 2
Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed
More informationConsider the following example where a base class has been derived by other two classes:
Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs
More informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationStandard I/O in C and C++
Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers
More information1. The term STL stands for?
1. The term STL stands for? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d 2. Which of the following statements regarding the
More informationUNIT V FILE HANDLING
UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:
More informationQUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING
QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT III PART - A (2 Marks) 1. What are the advantages of using exception handling? (AUC MAY 2013) In C++,
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationC++ Standard Template Library
C++ Standard Template Library CSE 333 Summer 2018 Instructor: Hal Perkins Teaching Assistants: Renshu Gu William Kim Soumya Vasisht C++ s Standard Library C++ s Standard Library consists of four major
More informationProgramming II with C++ (CSNB244) Lab 10. Topics: Files and Stream
Topics: Files and Stream In this lab session, you will learn very basic and most common I/O operations required for C++ programming. The second part of this tutorial will teach you how to read and write
More informationProgramming Languages Technical Specification for C++ Extensions for Parallelism
ISO 05 All rights reserved ISO/IEC JTC SC WG N4409 Date: 05-04-0 ISO/IEC DTS 9570 ISO/IEC JTC SC Secretariat: ANSI Programming Languages Technical Specification for C++ Extensions for Parallelism Warning
More informationChapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,
More informationFunction Templates. Consider the following function:
Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationStrings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationPIC10B/1 Winter 2014 Final Exam Study Guide
PIC10B/1 Winter 2014 Final Exam Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-24 inclusive) 2. Examples/Homework 3. Textbook The final exam will test 1. Your ability to read a program
More informationChapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag
More informationGridKa School 2013: Effective Analysis C++ Standard Template Library
GridKa School 2013: Effective Analysis C++ Standard Template Library Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg
More informationEL2310 Scientific Programming
Lecture 16: STL, C++1y (ramviyas@kth.se) Overview Overview Lecture 16: STL and C++1y Reminders Wrap up C++11 Reminders The help sessions and deadline C++ help session: Fri 24.10.2015, 15:00-17:00, Room
More informationChapte t r r 9
Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj
More informationDistributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes
Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented
More informationParallelism in C++ J. Daniel Garcia. Universidad Carlos III de Madrid. November 23, 2018
J. Daniel Garcia Universidad Carlos III de Madrid November 23, 2018 cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 1/58 Introduction to generic programming 1 Introduction to generic programming
More informationDeveloped By : Ms. K. M. Sanghavi
Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream
More informationConcurrency and Parallelism with C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting
Concurrency and Parallelism with C++17 and C++20 Rainer Grimm Training, Coaching and, Technology Consulting www.modernescpp.de Concurrency and Parallelism in C++ Concurrency and Parallelism in C++17 Parallel
More informationIntroduction to C++ Introduction to C++ 1
1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference
More information[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University
[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7 Seungkyu Lee Assistant Professor, Dept. of Computer Engineering Kyung Hee University Input entities Keyboard, files Output entities Monitor, files Standard
More informationFall 2017 CISC/CMPE320 9/27/2017
Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader
More informationTemplates C++ Primer Chapter 16
Lecture 8 Templates C++ Primer Chapter 16 Templates class template: Class definition used to define a set of type-specific classes. template MyClass {} function template: Definition
More informationC++ basics Getting started with, and Data Types.
C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding
More informationCS201 Solved MCQs.
15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.
More information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationfor (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;
// Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,
More informationFile I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents
File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or
More informationBITG 1113: Files and Stream LECTURE 10
BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output
More informationBITG 1233: Introduction to C++
BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token
More information