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.

Slides:



Advertisements
Similar presentations
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
Advertisements

I/O Streams as an Introduction to Objects and Classes
I/O and Program Control Statements Dick Steflik. Overloading C++ provides two types of overloading –function overloading the ability to use the same function.
Programming Stream Manipulators. COMP102 Prog. Fundamentals I: Stream Manipulator Slide 2 Stream Manipulators in iostream.h Library I/O stream manipulators.
1 Lecture 6: Input/Output (II) Introduction to Computer Science Spring 2006.
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.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 3: Input/Output
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.
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.
Chapter 12 Streams and File I/O. Learning Objectives I/O Streams – File I/O – Character I/O Tools for Stream I/O – File names as input – Formatting output,
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Definition Various stream manipulators can be used to specify the kinds of formatting to be performed during stream-I/O operations. Stream manipulators.
C++ Streams Lecture-2.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Fundamental File Processing Operations C++
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
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.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Chapter 3: Input/Output
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
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.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
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.
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.
Math Operators and Output Formatting. Incrementing and Decrementing StatementEquivalent Counter++;Counter = Counter + 1; ++Counter;Counter = Counter +
CS116 SENEM KUMOVA METİN. Outline What is C++ ? Some features of C++ Input and Output Operations Manipulators C++ header files Namespaces and scope resolution.
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.
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
Chapter 1.2 Introduction to C++ Programming
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
TMF1414 Introduction to Programming
Output Stream Formatting
Chapter 2 part #3 C++ Input / Output
Input and Output Chapter 3.
Standard Input/Output Streams
Standard Input/Output Streams
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.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 5 Input and Output Streams
Chapter 3: Input/Output
Chapter 3 Input output.
Chapter 4 INPUT AND OUTPUT OBJECTS
Programming with ANSI C ++
Formatted Input, Output & File Input, Output
Chapter 2 part #3 C++ Input / Output
Input/Output Streams, Part 2
Presentation transcript:

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 flows from an input device to the main memory ( from: keyboard, disk drive, scanner or network connection)  Output stream: A stream that flows from the main memory to an output device ( to: screen, printer, disk drive or network connection)‏

Working with Streams in C++ Like its predecessor C, C++ does not directly support input / output (I/O) operations However virtually all version of C++ now supply the standard iostreams template classes in the Standard C++ Library. File I/O in C++ uses the “File Stream” abstraction similar to that used with cin and cout To read from a file we can use the >> extraction operator To write to a file we use the << insertion operator

Standard iostream library Headers iostream: declares global stream objects that control all stream I/O operations (i.e: cin, cout )‏ iomanip: contains information useful for performing formatted I/O with parametrized stream manipulators fstream: contains information for performing files I/O operations

Stream Manipulators Manipulators are used to manipulate stream objects data in various ways They are typically used to format the output of different data types into a user specified way. These manipulators provide capabilities for  setting field widths,  setting precision,  setting and unsetting format flags  inserting a "newline"  skipping whitespace in input stream

Stream Manipulators boolalpha: flags a stream to insert or extract Boolean objects as names true and false instead of as numeric values (such as 1 and 0)‏ dec: flags a stream to insert or extract integer values in floating-point format (with decimals) fixed: flags a stream to insert floating-point values in fixed-point format, without using exponents. hex: flags a stream to insert or extract integer values in hexadecimal format. internal: adds fill characters (blanks by default) to a fill width as needed

Stream Manipulators left: flags a stream to left-justify characters by padding with fill characters on the right oct: flags a stream to insert or extract integer values in octal format. right: flags a stream to right-justify characters by padding with fill characters to the left scientific: flags a stream to insert floating point values in scientific format, using exponents showbase: flags a stream to insert a prefix that reveals the base of a generated integer field (for example hex 9 becomes 0x9)

Stream Manipulators showpoint: flags a stream to force a decimal point in a floating point field, even when there is no fractional part present showpos: flags a stream to insert a plus sign in a non- negative - generated numeric field. skipws: flags a stream to skip white-space before certain extractions unitbuf: sets the format flag to flush the output buffer after each insertion (otherwise an endl must be used)‏

Using manipulator to set Flags To set the cout manipulator flags we use the following cout methods As each of the manipulator flags are members of the class ios we need to use the :: scope resolution operator (more on this in a later lecture) to specify the flag as shown below We can specify the precision (number of decimal places) using the setprecision() method as follows cout.setf(flag to set); //set a flag cout.unsetf(flag to un-set) //unset a flag cout.setf(ios::showpos) //set a flag cout.unsetf(ios::showpos) //unset a flag cout << setprecision(2) << << endl;

#include using namespace std; void Display(float a[], int width); int main(void)‏ { float Afloat[2]={ , }; cout << "default format for true= "<<true<<" and false= "<<false<<endl; cout.setf(ios::boolalpha); cout << "setting boolalpha for true= "<<true<<" and false= "<<false<<endl; cout <<"Default numeric format"<<endl; Display(Afloat,10); cout <<"setting ios::showpoint "<<endl; cout.setf(ios::showpoint); Display(Afloat,10); cout <<"Setting ios::showpos" <<endl; cout.setf(ios::showpos); Display(Afloat,10); cout.unsetf(ios::showpos); cout <<"setting left justified"<<endl; cout.setf(ios::left); cout <<"Setting float precision to 2 decimal places"<<endl; cout.setf(ios::fixed);

cout<<setprecision(2)<< <<endl; cout <<"Setting ios::scientific"<<endl; Display(Afloat,10); cout.unsetf(ios::scientific); Display(Afloat,10); cout <<"setting ios::hex for value 34"<<endl; cout.setf(ios::hex,ios::basefield); cout.setf(ios::showbase); cout <<34<<endl; return 0; } void Display(float a[], int width)‏ { for(int i=0; i<2; i++)‏ { cout.width(width); cout <<a[i]<<endl; }

default format for true= 1 and false= 0 setting boolalpha for true= true and false= false Default numeric format 4.5e e+08 setting ios::showpoint e e+08 Setting ios::showpos e e+08 setting left justified Setting float precision to 2 decimal places Setting ios::scientific setting ios::hex for value 34 0x22 The program's Output

Converting Numbers to Strings #include using namespace std; int main(void)‏ { char Frames[50]; for(int i=0; i<30; i++)‏ { sprintf(Frames,"TestFrame.%06d.tiff",i); cout << Frames<<endl; } return 0; } #include using namespace std; int main(void)‏ { string Frames; stringstream s; for(int i=0; i<20; i++)‏ { s.fill('0'); s.width(3); s<<right<<i; Frames="TestFrame."+s.str()+".tiff"; cout << Frames<<endl; s.str(""); // clear the string } return 0; } C-way C++

Simplest to Convert a number to a string #include P3 #include using namespace std; string itos(double i)‏ { stringstream s; s << i; return s.str(); } int main(void)‏ { double i = ; string ss = itos(i); cout <<”integer= ” << i << endl; cout << “string= “ << ss << << endl; return 0; } double= string= Programme output

Using streams to access files The streams library also allows access to files using streams There are two basic methods for opening a file either for reading or writing These are set with the ios flags as follows To open a file we need to declare an object of type fstream which is the standard file stream object. All operation on the file then reference this object. ios::cout //open a file for writing a text ios::in //opens a file for reading a text

Using streams to access files When using files we use the following procedure  Create a file object  attempt to open the file (if it is not valid exit the program or issue a warning)‏  Loop until file read or write is done  close the file

File Processing File Open ? Get File Name Read/Write Finished ? Close File Report Error Open file END

File Input/Output When a file is opened a file descriptor is returned and this file descriptor is used for each subsequent I/O operation When a stream is opened the stream object created is used for all subsequent file operations not the file name.

Opening a File To open a file we need to create a file object of the correct type. Once this is done we use the open method to see if the file can be accessed. In the following example we open a file for writing too fstream FileIn; FileIn.open(argv[1],ios::in); if (!FileIn.is_open())‏ { cout <<"File : "<<argv[1]<<" Not found"<<endl; exit(1); }

Reading a text file and Printing its content #include P4 #include using namespace std; int main(int argc, char *argv[])‏ { if (argc <=1)‏ { cout <<"Usage FileRead [filename] "<<endl; exit(0); } fstream FileIn; FileIn.open(argv[1],ios::in); if (!FileIn.is_open())‏ { cout <<"File : "<<argv[1]<<" Not found"<<endl; exit(1); } string LineBuffer; unsigned long int LineNumber=1; while(!FileIn.eof())‏ { getline(FileIn,LineBuffer,'\n'); cout <<LineNumber<<" : "<<LineBuffer<<endl; LineNumber++; } FileIn.close(); return 0; }

g++ File1.cpp readline.cpp 1 : #include 2 : #include 3 : using namespace std; 4 : 5 : int main()‏ 6 : { 7 : cout << "Please enter a line:\n"; 8 : string s; 9 : getline(cin,s); 10 : cout << "You entered " << s << '\n'; 11 : }

Writing to a File #include P4 #include using namespace std; int main(int argc, char *argv[])‏ { if (argc <=1)‏ { cout <<"Usage FileWrite [filename] "<<endl; exit(0); } fstream FileOut; FileOut.open(argv[1],ios::out); if (!FileOut.is_open())‏ { cout <<"Could not open File : "<<argv[1]<<endl; exit(1); } for (int i=0; i<10; i++)‏ FileOut << "Line number is "<<i<<endl; FileOut.close(); return 0; } To write to a file we use ios::out flag as shown in the example

Binary File Reading The following example uses binary file I/O to create a user defined number of random points and save them to a file. The program then reads them back into a different structure and prints them out. Random Number generation is done using the following functions const int HALF_RAND = (RAND_MAX / 2); //returns a random number between +/- 1 float RandomNum(void)‏ { int rn; rn = rand(); return ((float)(rn - HALF_RAND) / (float)HALF_RAND); } /*! returns a random number between +/- MaxVal float RandomNum(float MaxVal)‏ { return MaxVal * RandomNum(); }

The Program #include using namespace std; // create a simple structure to hold the a simple 3D point class Point { public : float x; float y; float z; }; // pre-declare two Random number generating functions float RandomNum(void); float RandomNum(float MaxVal); int main(int argc, char *argv[])‏ { if (argc <=1)‏ { cout <<"Usage BinIO [filename] "<<endl; exit(0); }

The Program II // declare the File pointer object fstream File; int NumPoints=0; cout <<"Please enter the number of points to create"<<endl; cin >> NumPoints; // array of points to be written to a file Point *pointsOut = new Point [NumPoints]; // array of points to be read into the file Point *pointsIn = new Point [NumPoints]; // check we have a command line argument // set the random seed so we get different values each time we // run the program srand(time(NULL)); // Open the file for writing File.open(argv[1],ios::out|ios::binary); // if it isn't open exit if (!File.is_open())‏ { cout <<"Could not open File : "<<argv[1]<<" for writing”; exit(1); } // loop through and create a series of random points for(int i=0; i<NumPoints; i++)‏ { pointsOut[i].x=RandomNum(20); pointsOut[i].y=RandomNum(20); pointsOut[i].z=RandomNum(20); }

The Program III File.write(reinterpret_cast (&pointsOut[0]),sizeof(Point)*NumPoints); // close the file File.close(); // now open the file to Read from File.open(argv[1],ios::in|ios::binary); // check if ok else exit if (!File.is_open())‏ { cout <<"Could not open File : "<<argv[1]<<" for writing "<<endl; exit(1); } File.read(reinterpret_cast (&pointsIn[0]),sizeof(Point)*NumPoints); // now print out points for(int i=0; i<NumPoints; i++)‏ { cout <<"["<<pointsIn[i].x<<","<<pointsIn[i].y<<","<<pointsIn[i].z<<"]"<<endl; } File.close(); return 0; }

Reference