. Plab – Tirgul 8 I/O streams Example: string class.

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
Class template Describing a generic class Instantiating classes that are type-specific version of this generic class Also are called parameterized types.
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.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 File I/O 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.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
C++ Programming Certificate University of Washington Cliff Green
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
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.
C ++ Programming Languages Omid Jafarinezhad Lecturer: Omid Jafarinezhad Fall 2013 Lecture 2 Department of Computer Engineering 1.
Chapter 10C++ for Java Programmers1 Chapter 10 Input/Output.
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 Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Copyright 2008 Oxford Consulting, Ltd 1 October C to C++ C++ Comments Can use the symbol // To identify single line comments.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
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.
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:
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
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.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Lecture 14 Arguments, Classes and Files. Arguments.
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.
24 4/11/98 CSE 143 Stream I/O [Appendix C]. 25 4/11/98 Input/Output Concepts  Concepts should be review!  New syntax, but same fundamental concepts.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
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?
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
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 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.
CS212: Object Oriented Analysis and Design
Hank Childs, University of Oregon
Strings: C-strings vs. Strings as Objects
Introduction to C++ (Extensions to C)
Introduction to Programming
Overloading Operator MySting Example
14.4 Copy Constructors.
Standard Input/Output Streams
Standard Input/Output Streams
Operator Overloading.
Strings: C-strings vs. Strings as Objects
תכנות מכוון עצמים ו- C++ יחידה 06 העמסת אופרטורים
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3: Input/Output
Topics Input and Output Streams More Detailed Error Testing
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
File I/O.
COP 3330 Object-oriented Programming in C++
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
Presentation transcript:

. Plab – Tirgul 8 I/O streams Example: string class

Output stream C++ has a Stream I/O Library that supersedes C I/O functions. ostream is the type defined by the library for output streams. cout is an object of type ostream attached to stdout. Examples: #include cout << 7; cout << “Hello World\n”; #include cout << 7; cout << “Hello World\n”;

 The ostream overloads the << operator for each basic type (compare to toString() in Java). u The operator returns a reference to the output stream, which allows combined output: Output stream continued cout << “2 + 3 = “ << << endl; u endl is an example of manipulator. endl sends a ‘\n’ character to the stream and flushes it. u In fact endl is a function: << operator has a version that accepts a function pointer u cerr is similar to cout, it is attached to stderr.

Input stream istream is the type defined by the library for input streams. cin is an object of type istream attached to stdin. Examples: #include int i; char a[100]; cin >> i; // reads an int cin >> a; // reads till the 1 st space character #include int i; char a[100]; cin >> i; // reads an int cin >> a; // reads till the 1 st space character Note that >> skips whitespaces.

Input stream continued When an error occurs (typically because the input format is not what we expect) cin enters a failed state and evaluates to false. istream overloads the ! opeator and the void* (conversion) operator For example, to initialize an array we would write: int a[size]; for (int i = 0; i > a[i]; i++) ; int a[size]; for (int i = 0; i > a[i]; i++) ; In failed state istream will produce no input. Use clear() method to continue reading.

More I/O methods Both ostream and istream have additional methods: ostream& put(char ch) ostream& write(char const *str, int length) int get() // read one char istream& get(char& ch) // read one char getline(char *buffer, int size, int delimiter = '\n') Examples: cout.put(‘a’); char ch1, ch2, str[256]; cin.get(ch1).get(ch2); cin.getline(str, 256); cout.put(‘a’); char ch1, ch2, str[256]; cin.get(ch1).get(ch2); cin.getline(str, 256);

File streams To read from files we can use the ifstream, ofstream and fstream. Example: ofstream outFile(“out.txt”); outFile << “Hello world” << endl; int i; ifstream inFile(“in.txt”); while (inFile >> i) {... } int i; ifstream inFile(“in.txt”); while (inFile >> i) {... } Learn the details by yourselves.

. MyString

We would like to have a string class which will replace the inconvenient char*. class MyString { public: MyString(const char* ); MyString(const MyString& ); ~MyString(); int length() const; bool operator==(const MyString& ); private: void init(const char* ); int m_length; char* m_string; }; class MyString { public: MyString(const char* ); MyString(const MyString& ); ~MyString(); int length() const; bool operator==(const MyString& ); private: void init(const char* ); int m_length; char* m_string; }; copy c-tor

MyString.cpp MyString::init(const char* str) { m_string = new char[m_length]; for (int i = 0; i < m_length; i++) m_string[i] = str[i]; } MyString::MyString(const char* str){ m_length = strlen(str); init(str); } MyString::MyString(const MyString& str) { m_length = str.m_length; init(str.m_string); } MyString::init(const char* str) { m_string = new char[m_length]; for (int i = 0; i < m_length; i++) m_string[i] = str[i]; } MyString::MyString(const char* str){ m_length = strlen(str); init(str); } MyString::MyString(const MyString& str) { m_length = str.m_length; init(str.m_string); }

MyString.cpp continued int MyString::length() const { return m_length; } bool MyString::operator==(const MyString& str){ if (str.m_length != m_length) return false; int i; for (i = 0; m_string[i] == str.m_string[i] && i < m_length; i++) ; return (i == m_length); } MyString::~MyString() { if (m_string) delete [] m_string; } int MyString::length() const { return m_length; } bool MyString::operator==(const MyString& str){ if (str.m_length != m_length) return false; int i; for (i = 0; m_string[i] == str.m_string[i] && i < m_length; i++) ; return (i == m_length); } MyString::~MyString() { if (m_string) delete [] m_string; }

Using our string u Examples of using the string class: MyString a = “12345”; MyString b = a; MyString c = “6879”; if (a == c) {... } if (a == b) {... } MyString a = “12345”; MyString b = a; MyString c = “6879”; if (a == c) {... } if (a == b) {... } u But what about something like this? if (a == “123”) {... } It also works, by constructing MyString object from “123”, and using the operator== already defined.

Adding == u But what about something like this? if (“123” == a) {... } It is still undefined (and won’t compile).  To be able to compare C-style string with MyString we have to define a friend function: friend bool operator==(const char*, MyString&); bool operator== (const char* s1, MyString& s2) { // compare s1 with s2.m_string //... } inside MyString.h inside MyString.cpp

= operator  Since up to now we haven’t defined = operator, the default assignment operator is used. It performs a shallow copy, which is obviously not what we want.  If we want our strings to be immutable we should define the = operator as private (in.h file): private: MyString& operator=(const MyString& ); MyString& MyString::operator=(const MyString& s) { assert(false); } u It would be implemented like this:

= operator continued u Otherwise the operator is public public: MyString& operator=(const MyString& ); MyString& MyString::operator=(const MyString& s) { // delete m_string, copy s.m_string to m_string //... return *this; } MyString& MyString::operator=(const MyString& s) { // delete m_string, copy s.m_string to m_string //... return *this; } u It would be implemented like this: u Returning a reference to the object itself is essential for statements like: s1 = s2 = s3;

Swapping objects  After we have a well defined operator= we can write a swap function for MyString. void swap(MyString& s1, MyString& s2) { MyString temp = s1; s1 = s2; s2 = temp; } void swap(MyString& s1, MyString& s2) { MyString temp = s1; s1 = s2; s2 = temp; } u Compare to: (both in C++ and in Java) void swap(MyString s1, MyString s2) { MyString temp = s1; s1 = s2; s2 = temp; } void swap(MyString s1, MyString s2) { MyString temp = s1; s1 = s2; s2 = temp; }

operator[] u We can use [] to access individual characters in the string. char& MyString::operator[](int i) { return m_string[i]; } char& MyString::operator[](int i) { return m_string[i]; } u Examples of use: MyString a = “12345”; if (a[2] == ‘3’) {... } a[4] = ‘7’; MyString a = “12345”; if (a[2] == ‘3’) {... } a[4] = ‘7’; u Unfortunately it also allows: It will result in segfault in a ’s destructor (if not before). Why? delete [] &a[0];

Additional operators u Here are some additional operators we may want in our string class:  !=  + (to concatenate strings)  +=  < and <=  > and >=  etc...  In fact a string class is part of C++ standard library, it has all the features of MyString and much more…

I/O of MyString One of the advantages of using streams is the ability to define I/O operators for our own types. friend ostream& operator<<(ostream&, const MyString&); ostream& operator<<(ostream& os, const MyString& str) { os.write(str.m_string[i], str.m_length); return os; } Example: MyString a = "12345", b = "6789"; cout << a << “ “ << b << endl;

I/O of MyString continued friend istream& operator>>(istream&, MyString&); istream& operator>>(istream& is, MyString& str) { // read until whitespace, // extend str.m_string if required return is; } istream& operator>>(istream& is, MyString& str) { // read until whitespace, // extend str.m_string if required return is; } Example: MyString a = “”, b = “”; cin >> a >> b;