SlideShare a Scribd company logo
 
Chapter 6 I/O Streams as an Introduction to Objects and Classes Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
Overview 6.1  Streams and Basic File I/O  6.2  Tools for Stream I/O 6.3  Character I/O Slide 6-
6.1 Streams and Basic File I/O Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
I/O Streams I/O refers to program input and output Input is delivered to your program via a stream object Input can be from The keyboard A file Output is delivered to the output device via a stream object Output can be to  The screen A file Slide 6-
Objects Objects are special variables that Have their own special-purpose functions Set C++ apart from earlier programming languages Slide 6-
Streams and Basic File I/O Files for I/O are the same type of files used to store programs A stream is a flow of data. Input stream:  Data flows into the program If input stream flows from keyboard, the program will accept data from the keyboard If input stream flows from a file, the program will accept data from the file Output stream:  Data flows out of the program To the screen To a file Slide 6-
cin And cout Streams cin Input stream connected to the keyboard cout  Output stream connected to the screen cin and cout defined in the iostream library Use include directive:  #include <iostream> You can declare your own streams to use with  files. Slide 6-
Why Use Files? Files allow you to store data permanently! Data output to a file lasts after the program ends An input file can be used over and over No typing of data again and again for testing Create a data file or read an output file at your convenience Files allow you to deal with larger data sets Slide 6-
File I/O Reading from a file Taking input from a file Done from beginning to the end (for now) No backing up to read something again (OK to start over) Just as done from the keyboard Writing to a file Sending output to a file Done from beginning to end (for now) No backing up to write something again( OK to start over) Just as done to the screen Slide 6-
Stream Variables Like other variables, a stream variable…  Must be declared before it can be used Must be initialized before it contains valid data Initializing a stream means connecting it to a file The value of the stream variable can be thought of  as the file it is connected to Can have its value changed Changing a stream value means disconnecting from one file and connecting to another Slide 6-
Streams and Assignment  A stream is a special kind of variable called  an object Objects can use special functions to complete tasks Streams use special functions instead of the  assignment operator to change values Slide 6-
Declaring An  Input-file Stream Variable Input-file streams are of type ifstream Type ifstream  is defined in the fstream library You must use the include and using directives   #include <fstream>   using namespace std; Declare an input-file stream variable using    ifstream  in_stream; Slide 6-
Declaring An  Output-file Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library You must use these include and using directives   #include <fstream>   using namespace std; Declare an input-file stream variable using    ofstream  out_stream; Slide 6-
Once a stream variable is declared, connect it to a file Connecting a stream to a file is opening the file Use the open function of the stream object     in_stream.open(&quot;infile.dat&quot;); Connecting To A File Slide 6-  Period File name on the disk Double quotes
Using The Input Stream Once connected to a file, the input-stream  variable can be used to produce input just as you would use cin with the extraction operator Example:   int one_number, another_number;   in_stream >> one_number   >> another_number; Slide 6-
Using The Output Stream An output-stream works similarly to the  input-stream ofstream out_stream;  out_stream.open(&quot;outfile.dat&quot;);  out_stream << &quot;one number = &quot;   << one_number   << &quot;another number = &quot;    << another_number; Slide 6-
External File Names An External File Name… Is the name for a file that the operating system uses infile.dat and outfile.dat used in the previous examples Is the &quot;real&quot;, on-the-disk, name for a file  Needs to match the naming conventions on  your system Usually only used in the stream's open statement Once open, referred to using the  name of the stream connected to it. Slide 6-
After using a file, it should be closed This disconnects the stream from the file Close files to reduce the chance of a file being  corrupted if the program terminates abnormally It is important to close an output  file if your  program later needs to read input from the output file The system will automatically close files if you  forget as long as your program ends normally Closing a File Slide 6-  Display 6.1
Objects An object is a variable  that has functions and  data associated with it in_stream and out_stream each have a function named open associated with them in_stream and out_stream use  different  versions of a function named open  One version of open is for input files A different version of open is for output files Slide 6-
Member Functions A member function is a function associated with an object The open function is a member function of  in_stream in the previous examples A different open function is a member function of out_stream in the previous examples Slide 6-
Objects and  Member Function Names Objects of different types  have different member  functions Some of these member functions might have the same name Different objects of the same type have the same  member functions Slide 6-
Classes A type whose variables are objects, is a class ifstream is the type of the in_stream variable (object) ifstream is a class The class of an object determines its  member functions Example:   ifstream in_stream1, in_stream2; in_stream1.open and in_stream2.open are the same function but might have different arguments Slide 6-
Class Member Functions Member functions of an object are the member functions of its class The class determines the member functions of the object The class ifstream has an open function Every variable (object) declared of type ifstream  has that open function Slide 6-
Calling a Member Function Calling a member function requires specifying  the object containing the function The calling object  is separated from the member  function by the dot operator Example:  in_stream.open(&quot;infile.dat&quot;); Slide 6-  Calling object Dot operator Member function
Member Function  Calling Syntax Syntax for calling a member function: Calling_object.Member_Function_Name(Argument_list); Slide 6-
Errors On Opening Files Opening a file could fail for several reasons Common reasons for open to fail include The file might not exist The name might be typed incorrectly May be no error message if the call to open fails Program execution continues! Slide 6-
Catching Stream Errors Member function fail, can be used to test the  success of a stream operation fail returns a boolean type  (true or false) fail returns true if the stream operation failed Slide 6-
Halting Execution When a stream open function fails, it is  generally best to stop the program The function exit, halts a program exit returns its argument to the operating system exit causes program execution to stop exit is NOT a member function Exit requires the include and using directives   #include <cstdlib>   using namespace std; Slide 6-
Immediately following the call to open, check  that the operation was successful:   in_stream.open(&quot;stuff.dat&quot;);   if( in_stream.fail( ) )   {    cout << &quot;Input file opening failed.\n&quot;;   exit(1) ;   } Using  fail and exit Slide 6-  Display 6.2
Techniques for File I/O When reading input from a file… Do not include prompts or echo the  input The lines  cout << &quot;Enter the number: &quot;;   cin  >> the_number;   cout << &quot;The number you entered is &quot;    << the_number; become  just one line   in_file >> the_number; The input file must contain exactly the data expected Slide 6-
Output examples so far create new files If the output file already contains data, that data is lost To append new output to the end an existing file use the constant  ios::app defined in the iostream  library:    outStream.open(&quot;important.txt&quot;, ios::app); If the file does not exist, a new file will be created Appending Data (optional) Slide 6-  Display 6.3
File Names as Input (optional) Program users can enter the name of a file to  use for input or for output Program must use a variable that can hold  multiple characters  A sequence of characters is called a string  Declaring a variable to hold a string of characters:    char  file_name[16]; file_name is the name of a variable Brackets enclose the maximum number of characters + 1  The variable file_name contains up to 15 characters Slide 6-
char file_name[16]; cout << &quot;Enter the file_name &quot;; cin >> file_name; ifstream in_stream; in_stream.open(file_name); if (in_stream.fail( ) ) {    cout << &quot;Input file opening failed.\n&quot;;   exit(1); } Using A Character String Slide 6-  Display 6.4 (1) Display 6.4 (2)
Section 6.1 Conclusion Can you Write a program that uses a stream called fin which  will be connected to an input file and a stream called fout which will be connected to an output file?  How do you declare fin and fout?  What include  directive, if any, do you nee to place in your program file? Name at least three member functions of an  iostream object and give examples of usage of  each? Slide 6-
6.2 Tools for Streams I/O Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
Tools for Stream I/O To control the format of the program's output  We use commands that determine such details as: The spaces between items The number of digits after a decimal point The numeric style: scientific notation for fixed point Showing digits after a decimal point even if they are zeroes Showing plus signs in front of positive numbers Left or right justifying numbers in a given space Slide 6-
Formatting Output to Files Format output to the screen with:   cout.setf(ios::fixed); cout.setf(ios::showpoint);   cout.precision(2); Format output to a file using the out-file stream  named out_stream with: out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint);   out_stream.precision(2); Slide 6-
out_stream.precision(2); precision is a member function of output streams After out_stream.precision(2); Output of numbers with decimal points… will show a total of 2 significant digits   23. 2.2e7   2.2   6.9e-1 0.00069 OR will show  2 digits after the decimal point 23.56 2.26e7   2.21   0.69 0.69e-4 Calls to precision apply only to the stream named in the call Slide 6-
setf(ios::fixed); setf is a member function of output streams setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag  After  out_stream.setf(ios::fixed); All further output of floating point numbers… Will be written in fixed-point notation, the way we  normally expect to see numbers  Calls to setf apply only to the stream named in the call Slide 6-
After out_stream.setf(ios::showpoint); Output of floating point numbers… Will show the decimal point even if all digits after the decimal point are zeroes setf(ios::showpoint); Slide 6-  Display 6.5
Creating Space in Output The width function specifies the number of  spaces for the next item Applies only to the next item of output Example: To print the digit 7 in four spaces use     out_stream.width(4);     out_stream << 7 << endl; Three of the spaces will be blank Slide 6-  (ios::right) (ios::left) 7   7
Not Enough Width? What if the argument for width is too small? Such as specifying   cout.width(3);  when the value to print is 3456.45 The entire item is always output If too few spaces are specified, as many more  spaces as needed are used Slide 6-
Unsetting Flags Any flag that is set, may be unset Use the unsetf function Example: cout.unsetf(ios::showpos); causes the program to stop printing plus signs on positive numbers Slide 6-
Manipulators A manipulator is a function called in a  nontraditional way Manipulators in turn call member functions Manipulators may or may not have arguments Used after the insertion operator (<<) as if the  manipulator function call is an output item Slide 6-
The setw Manipulator setw does the same task as the member  function width setw calls the width function to set spaces for output Example:  cout << &quot;Start&quot; << setw(4) << 10     << setw(4) << setw(6) << 30; produces:  Start  10  20  30 Slide 6-  Two Spaces Four Spaces
The setprecision Manipulator setprecision does the same task as the member  function precision Example:  cout.setf(ios::fixed);   cout.setf(ios::showpoint);   cout << &quot;$&quot; << setprecision(2) << 10.3  << endl << &quot;$&quot; << 20.5 << endl;     produces:  $10.30   $20.50 setprecision setting stays in effect until changed Slide 6-
Manipulator Definitions The manipulators setw and setprecision are  defined in the iomanip library To use these manipulators, add these lines  #include <iomanip> using namespace std; Slide 6-
Stream Names as Arguments Streams can be arguments to a function The function's formal parameter for the stream must be call-by-reference  Example:  void make_neat(ifstream& messy_file,    ofstream&  neat_file); Slide 6-
The End of The File Input files used by a program may vary in length Programs may not be able to assume the number of items in the file A way to know the end of the file is reached: The boolean expression (in_stream >> next) Reads a value from in_stream and stores it in next True if a value can be read and stored in next False if there is not a value to be read (the end of the file) Slide 6-
End of File Example To calculate the average of the numbers in a file   double next, sum = 0;   int count = 0;   while(in_stream >> next)   { sum = sum + next;   count++;   }   double average = sum / count; Slide 6-
Stream Arguments  and Namespaces Using directives have been local to function  definitions in the examples so far When parameter type names are in a namespace A using directive must be outside the function so C++ will understand the parameter type names such as ifstream Easy solution is to place the using directive at the beginning of the file Many experts do not approve as this does not allow  using multiple namespaces with names in common Slide 6-
The program in Display 6.6… Takes input from rawdata.dat Writes output to the screen and to neat.dat Formatting instructions are used to create a neater layout Numbers are written one per line in a field width of 12 Each number is written with 5 digits after the decimal point Each number is written with a plus or minus sign Uses function make_neat that has formal parameters for the input-file stream and output-file stream Program Example Slide 6-  Display 6.6 (1) Display 6.6 (2) Display 6.6 (3)
Section 6.2 Conclusion Can you Show the output produced when the following line  is executed? cout << &quot;*&quot; << setw(3) << 12345 << &quot;*&quot; endl; Describe the effect of each of these flags? Ios::fixed  ios::scientific ios::showpoint ios::right ios::right ios::showpos Slide 6-
6.3 Character I/O Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
Character I/O All data is input and output as characters Output of the number 10 is two characters '1' and '0' Input of the number 10 is also done as '1' and '0' Interpretation of 10 as the number 10 or as characters depends on the program Conversion between characters and numbers is usually automatic Slide 6-
Low Level Character I/O Low level C++ functions for character I/O Perform character input and output  Do not perform automatic conversions Allow you to do input and output in anyway you can devise Slide 6-
Member Function get Function get Member function of every input stream Reads one character from an input stream Stores the character read in a variable of type char, the single argument the function takes Does not use the extraction operator (>>)  which performs some automatic work Does not skip blanks Slide 6-
Using get These lines use get to read a character and store  it in the variable next_symbol char next_symbol;   cin.get(next_symbol); Any character will be read with these statements Blank spaces too! '\n' too!  (The newline character) Slide 6-
get Syntax input_stream.get(char_variable); Examples:  char  next_symbol; cin.get(next_symbol); ifstream  in_stream; in_stream.open(&quot;infile.dat&quot;); in_stream.get(next_symbol); Slide 6-
More About get Given this code: char c1, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); and this input:   AB   CD c1 = 'A'  c2 = 'B'  c3 = '\n' cin >> c1 >> c2 >> c3;  would place 'C' in c3 (the &quot;>>&quot; operator skips the newline character) Slide 6-
The End of The Line To read and echo a line of input Look for '\n' at the end of the input line:   cout<<&quot;Enter a line of input and I will &quot;   << &quot;echo it.\n&quot;;   char symbol;   do   {     cin.get(symbol);     cout << symbol; } while (symbol != '\n'); All characters, including '\n' will be output Slide 6-
'\n ' vs &quot;\n &quot; '\n' A value of type char Can be stored in a variable of type char &quot;\n&quot; A string containing only one character Cannot be stored in a variable of type char In a cout-statement they produce the same result Slide 6-
Member Function put Function put Member function of every output stream Requires one argument of type char Places its argument of type char in the output stream Does not do allow you to do more than previous output with the insertion operator and cout Slide 6-
put Syntax Output_stream.put(Char_expression); Examples:  cout.put(next_symbol);     cout.put('a');     ofstream out_stream;   out_stream.open(&quot;outfile.dat&quot;);   out_stream.put('Z');  Slide 6-
Member Function putback The putback member function places a character  in the input stream putback is a member function of every input stream Useful when input continues until a specific character is read, but you do not want to process the character Places its argument of type char in the input stream Character placed in the stream does not have to be a character read from the stream Slide 6-
putback Example The following code reads up to the first blank in  the input stream fin, and writes the characters to the file connected to the output stream fout fin.get(next);   while (next != '  ')   {   fout.put(next);   fin.get(next);   }   fin.putback(next); The blank space read to end the loop is put back into  the input stream Slide 6-
Program Example Checking Input Incorrect input can produce worthless output Use input functions that allow the user to  re-enter input until it is correct, such as Echoing the input and asking the user if it is correct If the input is not correct, allow the user to enter the data again Slide 6-
Checking Input: get_int The get_int function seen in Display 6.7 obtains an integer value from the user get_int prompts the user, reads the input, and displays the input After displaying the input, get_int asks the user to  confirm the number and reads the user's response using a variable of type character The process is repeated until the user indicates with a 'Y' or 'y' that the number entered is correct Slide 6-
The new_line function seen in Display 6.7 is  called by the get_int function new_line reads all the characters remaining in the  input line but does nothing with them, essentially  discarding them new_line is used to discard what follows the first  character of the the user's response to get_line's  &quot;Is that correct? (yes/no)&quot; The newline character is  discarded as well Checking Input: new_line Slide 6-  Display 6.7 (1) Display 6.7 (2)
Checking Input: Check for Yes or No? get_int continues to ask for a number until the user responds  'Y' or 'y' using the do-while loop   do   {    // the loop body } while  ((ans !='Y') &&(ans != 'y') ) Why not use ((ans =='N') | | (ans == 'n') )? User must enter a correct response to continue  a loop tested with ((ans =='N') | | (ans == 'n') ) What if they mis-typed &quot;Bo&quot; instead of &quot;No&quot;? User must enter a correct response to end the loop tested with ((ans !='Y') &&(ans != 'y') ) Slide 6-
Mixing cin >> and cin.get Be sure to deal with the '\n' that ends each  input line if using cin >> and cin.get &quot;cin >>&quot;  reads up to the '\n' The '\n' remains in the input stream Using cin.get  next will read the '\n' The new_line function from Display 6.7 can be used to clear the '\n' Slide 6-
'\n' Example The Code:  cout << &quot;Enter a number:\n&quot;; int number; cin >> number; cout << &quot;Now enter a letter:\n&quot;; char symbol; cin.get(symbol); Slide 6-  The Dialogue: Enter a number: 21 Now enter a letter: A The Result: number = 21 symbol = '\n'
A Fix To Remove '\n' cout << &quot;Enter a number:\n&quot;; int number; cin >> number; cout << &quot;Now enter a letter:\n&quot;; char symbol; cin >>symbol; Slide 6-
Another  '\n' Fix cout << &quot;Enter a number:\n&quot;; int number; cin >> number; new_line( ); // From Display 6.7 cout << &quot;Now enter a letter:\n&quot;; char symbol; cin.get(symbol); Slide 6-
Detecting the End of a File Member function eof detects the end of a file Member function of every input-file stream eof stands for end of file eof returns a boolean value  True when the end of the file has been reached False when there is more data to read Normally used to determine when we are NOT  at the end of the file Example:  if ( ! in_stream.eof( ) ) Slide 6-
Using eof This loop reads each character, and writes it to the screen in_stream.get(next); while (! in_stream.eof( ) )   {   cout << next;   in_stream.get(next);   } ( ! In_stream.eof( ) ) becomes false when the  program reads past the last character in the file Slide 6-
The End Of File Character End of a file is indicated by a special character in_stream.eof( ) is still true after the last  character of data is read in_stream.eof( ) becomes false when the  special end of file character is read  Slide 6-
How To Test End of File We have seen two methods while ( in_stream >> next) while ( ! in_stream.eof( ) ) Which should be used? In general, use eof when input is treated as text and using a member function get to read input In general, use the extraction operator method when processing numeric data Slide 6-
The program of Display 6.8… Reads every character of file cad.dat and copies it to file cplusad.dat except that every 'C' is changed to &quot;C++&quot; in cplusad.dat Preserves line breaks in cad.dat get is used for input as the extraction operator would skip line breaks get is used to preserve spaces as well Uses eof to test for end of file Program Example: Editing a Text File Slide 6-  Display 6.8 (1) Display 6.8 (2)
Character Functions Several predefined functions exist to facilitate  working with characters The cctype library is required #include <cctype> using namespace std; Slide 6-
The toupper Function toupper  returns the argument's upper case  character  toupper('a')  returns 'A' toupper('A') return 'A' Slide 6-
toupper Returns An int Characters are actually stored as an integer  assigned to the character toupper and tolower actually return the integer representing the character cout << toupper('a');  //prints the integer for 'A' char c = toupper('a');  //places the integer for 'A' in c cout << c;    //prints 'A' cout << static_cast<char>(toupper('a'));  //works too Slide 6-
isspace returns true if the argument is whitespace Whitespace is spaces, tabs, and newlines isspace('  ') returns true Example:  if (isspace(next) )   cout << '-';   else cout << next; Prints a '-' if next contains a space, tab, or  newline character See more character functions in  The isspace Function Slide 6-  Display 6.9 (1) Display 6.9 (2)
Section 6.3 Conclusion Can you Write code that will read a line of text and echo the line with all the uppercase letters deleted? Describe two methods to detect the end of an input file: Describe whitespace? Slide 6-
Chapter 6 -- End Slide 6-
Display 6.1  Slide 6-  Back Next
Display 6.2 Slide 6-  Back Next
Display 6.3 Slide 6-  Back Next
Display 6.4 (1/2) Slide 6-  Back Next
Display 6.4 (2/2) Slide 6-  Back Next
Display 6.5 Slide 6-  Back Next
Display 6.6 (1/3) Slide 6-  Back Next
Display 6.6  (2/3) Slide 6-  Back Next
Display 6.6 (3/3) Slide 6-  Back Next
Display 6.7  (1/2)   Slide 6-  Back Next
Display 6.7  (2/2) Slide 6-  Back Next
Display 6.8  (1/2) Slide 6-  Next Back
Display 6.8  (2/2) Slide 6-  Back Next
Display 6.9 (1/2) Slide 6-  Back Next
Display 6.9  (2/2) Slide 6-  Back Next

More Related Content

PPT
Savitch ch 06
Terry Yoast
 
PPT
File Input & Output
PRN USM
 
PPTX
Input/Output Exploring java.io
NilaNila16
 
PPTX
Chapter 08 data file handling
Praveen M Jigajinni
 
PDF
Java I/O
Jussi Pohjolainen
 
PPT
Jsr75 sup
SMIJava
 
PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
ODP
IO In Java
parag
 
Savitch ch 06
Terry Yoast
 
File Input & Output
PRN USM
 
Input/Output Exploring java.io
NilaNila16
 
Chapter 08 data file handling
Praveen M Jigajinni
 
Jsr75 sup
SMIJava
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 
IO In Java
parag
 

What's hot (20)

PPTX
Understanding java streams
Shahjahan Samoon
 
PDF
Files in java
Muthukumaran Subramanian
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
Input output files in java
Kavitha713564
 
PPTX
Java Input Output (java.io.*)
Om Ganesh
 
PPT
14 file handling
APU
 
PPT
Java stream
Arati Gadgil
 
PDF
32.java input-output
santosh mishra
 
PPT
Byte stream classes.49
myrajendra
 
PPTX
L21 io streams
teach4uin
 
PPT
Spsl iv unit final
Sasidhar Kothuru
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPT
Chapter09
Rajesh Mandava
 
PPTX
Multithreading in java
Kavitha713564
 
PPT
CustomizingStyleSheetsForHTMLOutputs
Suite Solutions
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PPTX
Overview of XSL, XPath and XSL-FO
Suite Solutions
 
PPT
R12 d49656 gc10-apps dba 05
zeesniper
 
PDF
Java IO
UTSAB NEUPANE
 
Understanding java streams
Shahjahan Samoon
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java I/o streams
Hamid Ghorbani
 
Input output files in java
Kavitha713564
 
Java Input Output (java.io.*)
Om Ganesh
 
14 file handling
APU
 
Java stream
Arati Gadgil
 
32.java input-output
santosh mishra
 
Byte stream classes.49
myrajendra
 
L21 io streams
teach4uin
 
Spsl iv unit final
Sasidhar Kothuru
 
Java Streams
M Vishnuvardhan Reddy
 
Chapter09
Rajesh Mandava
 
Multithreading in java
Kavitha713564
 
CustomizingStyleSheetsForHTMLOutputs
Suite Solutions
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Overview of XSL, XPath and XSL-FO
Suite Solutions
 
R12 d49656 gc10-apps dba 05
zeesniper
 
Java IO
UTSAB NEUPANE
 
Ad

Viewers also liked (20)

PPT
Savitch Ch 13
Terry Yoast
 
PPT
Savitch Ch 15
Terry Yoast
 
PPT
Savitch ch 022
Dr .Ahmed Tawwab
 
PPT
Savitch Ch 17
Terry Yoast
 
PPT
Savitch Ch 03
Terry Yoast
 
PPT
Savitch Ch 18
Terry Yoast
 
PPT
Savitch Ch 12
Terry Yoast
 
PPT
Savitch Ch 10
Terry Yoast
 
PPT
Savitch Ch 02
Terry Yoast
 
PPT
Savitch Ch 07
Terry Yoast
 
PPT
Savitch c++ ppt figs ch1
Terry Yoast
 
PPT
Savitch Ch 08
Terry Yoast
 
PPT
Savitch ch 16
Terry Yoast
 
PPT
Savitch Ch 11
Terry Yoast
 
PPT
Savitch ch 04
Terry Yoast
 
PPT
Savitch Ch 01
Terry Yoast
 
PPT
Savitch Ch 14
Terry Yoast
 
PPT
Savitch ch 01
Terry Yoast
 
PPT
Savitch Ch 04
Terry Yoast
 
PPT
Savitch Ch 05
Terry Yoast
 
Savitch Ch 13
Terry Yoast
 
Savitch Ch 15
Terry Yoast
 
Savitch ch 022
Dr .Ahmed Tawwab
 
Savitch Ch 17
Terry Yoast
 
Savitch Ch 03
Terry Yoast
 
Savitch Ch 18
Terry Yoast
 
Savitch Ch 12
Terry Yoast
 
Savitch Ch 10
Terry Yoast
 
Savitch Ch 02
Terry Yoast
 
Savitch Ch 07
Terry Yoast
 
Savitch c++ ppt figs ch1
Terry Yoast
 
Savitch Ch 08
Terry Yoast
 
Savitch ch 16
Terry Yoast
 
Savitch Ch 11
Terry Yoast
 
Savitch ch 04
Terry Yoast
 
Savitch Ch 01
Terry Yoast
 
Savitch Ch 14
Terry Yoast
 
Savitch ch 01
Terry Yoast
 
Savitch Ch 04
Terry Yoast
 
Savitch Ch 05
Terry Yoast
 
Ad

Similar to Savitch Ch 06 (20)

PPT
I/O Streams as an Introduction to Objects and Classesppt
PKTuber05
 
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
PPTX
Introduction to files management systems
araba8
 
PPTX
Stream classes in C++
Shyam Gupta
 
PPTX
File Handling
AlgeronTongdoTopi
 
PPTX
File Handling
AlgeronTongdoTopi
 
PDF
VIT351 Software Development VI Unit5
YOGESH SINGH
 
PPTX
File Management and manipulation in C++ Programming
ChereLemma2
 
PPT
Chapter 11
Terry Yoast
 
PPTX
File management in C++
apoorvaverma33
 
PPTX
Chapter4.pptx
WondimuBantihun1
 
PPTX
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
drkangurajuphd
 
PDF
Data file handling
Prof. Dr. K. Adisesha
 
PPTX
File Handling.pptx
PragatiSutar4
 
PDF
File Handling.pdffile handling ppt final
e13225064
 
DOCX
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
PPT
7 Data File Handling
Praveen M Jigajinni
 
PPTX
Basics of file handling
pinkpreet_kaur
 
PPTX
basics of file handling
pinkpreet_kaur
 
I/O Streams as an Introduction to Objects and Classesppt
PKTuber05
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Introduction to files management systems
araba8
 
Stream classes in C++
Shyam Gupta
 
File Handling
AlgeronTongdoTopi
 
File Handling
AlgeronTongdoTopi
 
VIT351 Software Development VI Unit5
YOGESH SINGH
 
File Management and manipulation in C++ Programming
ChereLemma2
 
Chapter 11
Terry Yoast
 
File management in C++
apoorvaverma33
 
Chapter4.pptx
WondimuBantihun1
 
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
drkangurajuphd
 
Data file handling
Prof. Dr. K. Adisesha
 
File Handling.pptx
PragatiSutar4
 
File Handling.pdffile handling ppt final
e13225064
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
7 Data File Handling
Praveen M Jigajinni
 
Basics of file handling
pinkpreet_kaur
 
basics of file handling
pinkpreet_kaur
 

More from Terry Yoast (20)

PPT
9781305078444 ppt ch12
Terry Yoast
 
PPT
9781305078444 ppt ch11
Terry Yoast
 
PPT
9781305078444 ppt ch10
Terry Yoast
 
PPT
9781305078444 ppt ch09
Terry Yoast
 
PPT
9781305078444 ppt ch08
Terry Yoast
 
PPT
9781305078444 ppt ch07
Terry Yoast
 
PPT
9781305078444 ppt ch06
Terry Yoast
 
PPT
9781305078444 ppt ch05
Terry Yoast
 
PPT
9781305078444 ppt ch04
Terry Yoast
 
PPT
9781305078444 ppt ch03
Terry Yoast
 
PPT
9781305078444 ppt ch02
Terry Yoast
 
PPT
9781305078444 ppt ch01
Terry Yoast
 
PPTX
9781337102087 ppt ch13
Terry Yoast
 
PPTX
9781337102087 ppt ch18
Terry Yoast
 
PPTX
9781337102087 ppt ch17
Terry Yoast
 
PPTX
9781337102087 ppt ch16
Terry Yoast
 
PPTX
9781337102087 ppt ch15
Terry Yoast
 
PPTX
9781337102087 ppt ch14
Terry Yoast
 
PPTX
9781337102087 ppt ch12
Terry Yoast
 
PPTX
9781337102087 ppt ch11
Terry Yoast
 
9781305078444 ppt ch12
Terry Yoast
 
9781305078444 ppt ch11
Terry Yoast
 
9781305078444 ppt ch10
Terry Yoast
 
9781305078444 ppt ch09
Terry Yoast
 
9781305078444 ppt ch08
Terry Yoast
 
9781305078444 ppt ch07
Terry Yoast
 
9781305078444 ppt ch06
Terry Yoast
 
9781305078444 ppt ch05
Terry Yoast
 
9781305078444 ppt ch04
Terry Yoast
 
9781305078444 ppt ch03
Terry Yoast
 
9781305078444 ppt ch02
Terry Yoast
 
9781305078444 ppt ch01
Terry Yoast
 
9781337102087 ppt ch13
Terry Yoast
 
9781337102087 ppt ch18
Terry Yoast
 
9781337102087 ppt ch17
Terry Yoast
 
9781337102087 ppt ch16
Terry Yoast
 
9781337102087 ppt ch15
Terry Yoast
 
9781337102087 ppt ch14
Terry Yoast
 
9781337102087 ppt ch12
Terry Yoast
 
9781337102087 ppt ch11
Terry Yoast
 

Recently uploaded (20)

PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
CDH. pptx
AneetaSharma15
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
CDH. pptx
AneetaSharma15
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 

Savitch Ch 06

  • 1.  
  • 2. Chapter 6 I/O Streams as an Introduction to Objects and Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 3. Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-
  • 4. 6.1 Streams and Basic File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 5. I/O Streams I/O refers to program input and output Input is delivered to your program via a stream object Input can be from The keyboard A file Output is delivered to the output device via a stream object Output can be to The screen A file Slide 6-
  • 6. Objects Objects are special variables that Have their own special-purpose functions Set C++ apart from earlier programming languages Slide 6-
  • 7. Streams and Basic File I/O Files for I/O are the same type of files used to store programs A stream is a flow of data. Input stream: Data flows into the program If input stream flows from keyboard, the program will accept data from the keyboard If input stream flows from a file, the program will accept data from the file Output stream: Data flows out of the program To the screen To a file Slide 6-
  • 8. cin And cout Streams cin Input stream connected to the keyboard cout Output stream connected to the screen cin and cout defined in the iostream library Use include directive: #include <iostream> You can declare your own streams to use with files. Slide 6-
  • 9. Why Use Files? Files allow you to store data permanently! Data output to a file lasts after the program ends An input file can be used over and over No typing of data again and again for testing Create a data file or read an output file at your convenience Files allow you to deal with larger data sets Slide 6-
  • 10. File I/O Reading from a file Taking input from a file Done from beginning to the end (for now) No backing up to read something again (OK to start over) Just as done from the keyboard Writing to a file Sending output to a file Done from beginning to end (for now) No backing up to write something again( OK to start over) Just as done to the screen Slide 6-
  • 11. Stream Variables Like other variables, a stream variable… Must be declared before it can be used Must be initialized before it contains valid data Initializing a stream means connecting it to a file The value of the stream variable can be thought of as the file it is connected to Can have its value changed Changing a stream value means disconnecting from one file and connecting to another Slide 6-
  • 12. Streams and Assignment A stream is a special kind of variable called an object Objects can use special functions to complete tasks Streams use special functions instead of the assignment operator to change values Slide 6-
  • 13. Declaring An Input-file Stream Variable Input-file streams are of type ifstream Type ifstream is defined in the fstream library You must use the include and using directives #include <fstream> using namespace std; Declare an input-file stream variable using ifstream in_stream; Slide 6-
  • 14. Declaring An Output-file Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library You must use these include and using directives #include <fstream> using namespace std; Declare an input-file stream variable using ofstream out_stream; Slide 6-
  • 15. Once a stream variable is declared, connect it to a file Connecting a stream to a file is opening the file Use the open function of the stream object in_stream.open(&quot;infile.dat&quot;); Connecting To A File Slide 6- Period File name on the disk Double quotes
  • 16. Using The Input Stream Once connected to a file, the input-stream variable can be used to produce input just as you would use cin with the extraction operator Example: int one_number, another_number; in_stream >> one_number >> another_number; Slide 6-
  • 17. Using The Output Stream An output-stream works similarly to the input-stream ofstream out_stream; out_stream.open(&quot;outfile.dat&quot;); out_stream << &quot;one number = &quot; << one_number << &quot;another number = &quot; << another_number; Slide 6-
  • 18. External File Names An External File Name… Is the name for a file that the operating system uses infile.dat and outfile.dat used in the previous examples Is the &quot;real&quot;, on-the-disk, name for a file Needs to match the naming conventions on your system Usually only used in the stream's open statement Once open, referred to using the name of the stream connected to it. Slide 6-
  • 19. After using a file, it should be closed This disconnects the stream from the file Close files to reduce the chance of a file being corrupted if the program terminates abnormally It is important to close an output file if your program later needs to read input from the output file The system will automatically close files if you forget as long as your program ends normally Closing a File Slide 6- Display 6.1
  • 20. Objects An object is a variable that has functions and data associated with it in_stream and out_stream each have a function named open associated with them in_stream and out_stream use different versions of a function named open One version of open is for input files A different version of open is for output files Slide 6-
  • 21. Member Functions A member function is a function associated with an object The open function is a member function of in_stream in the previous examples A different open function is a member function of out_stream in the previous examples Slide 6-
  • 22. Objects and Member Function Names Objects of different types have different member functions Some of these member functions might have the same name Different objects of the same type have the same member functions Slide 6-
  • 23. Classes A type whose variables are objects, is a class ifstream is the type of the in_stream variable (object) ifstream is a class The class of an object determines its member functions Example: ifstream in_stream1, in_stream2; in_stream1.open and in_stream2.open are the same function but might have different arguments Slide 6-
  • 24. Class Member Functions Member functions of an object are the member functions of its class The class determines the member functions of the object The class ifstream has an open function Every variable (object) declared of type ifstream has that open function Slide 6-
  • 25. Calling a Member Function Calling a member function requires specifying the object containing the function The calling object is separated from the member function by the dot operator Example: in_stream.open(&quot;infile.dat&quot;); Slide 6- Calling object Dot operator Member function
  • 26. Member Function Calling Syntax Syntax for calling a member function: Calling_object.Member_Function_Name(Argument_list); Slide 6-
  • 27. Errors On Opening Files Opening a file could fail for several reasons Common reasons for open to fail include The file might not exist The name might be typed incorrectly May be no error message if the call to open fails Program execution continues! Slide 6-
  • 28. Catching Stream Errors Member function fail, can be used to test the success of a stream operation fail returns a boolean type (true or false) fail returns true if the stream operation failed Slide 6-
  • 29. Halting Execution When a stream open function fails, it is generally best to stop the program The function exit, halts a program exit returns its argument to the operating system exit causes program execution to stop exit is NOT a member function Exit requires the include and using directives #include <cstdlib> using namespace std; Slide 6-
  • 30. Immediately following the call to open, check that the operation was successful: in_stream.open(&quot;stuff.dat&quot;); if( in_stream.fail( ) ) { cout << &quot;Input file opening failed.\n&quot;; exit(1) ; } Using fail and exit Slide 6- Display 6.2
  • 31. Techniques for File I/O When reading input from a file… Do not include prompts or echo the input The lines cout << &quot;Enter the number: &quot;; cin >> the_number; cout << &quot;The number you entered is &quot; << the_number; become just one line in_file >> the_number; The input file must contain exactly the data expected Slide 6-
  • 32. Output examples so far create new files If the output file already contains data, that data is lost To append new output to the end an existing file use the constant ios::app defined in the iostream library: outStream.open(&quot;important.txt&quot;, ios::app); If the file does not exist, a new file will be created Appending Data (optional) Slide 6- Display 6.3
  • 33. File Names as Input (optional) Program users can enter the name of a file to use for input or for output Program must use a variable that can hold multiple characters A sequence of characters is called a string Declaring a variable to hold a string of characters: char file_name[16]; file_name is the name of a variable Brackets enclose the maximum number of characters + 1 The variable file_name contains up to 15 characters Slide 6-
  • 34. char file_name[16]; cout << &quot;Enter the file_name &quot;; cin >> file_name; ifstream in_stream; in_stream.open(file_name); if (in_stream.fail( ) ) { cout << &quot;Input file opening failed.\n&quot;; exit(1); } Using A Character String Slide 6- Display 6.4 (1) Display 6.4 (2)
  • 35. Section 6.1 Conclusion Can you Write a program that uses a stream called fin which will be connected to an input file and a stream called fout which will be connected to an output file? How do you declare fin and fout? What include directive, if any, do you nee to place in your program file? Name at least three member functions of an iostream object and give examples of usage of each? Slide 6-
  • 36. 6.2 Tools for Streams I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 37. Tools for Stream I/O To control the format of the program's output We use commands that determine such details as: The spaces between items The number of digits after a decimal point The numeric style: scientific notation for fixed point Showing digits after a decimal point even if they are zeroes Showing plus signs in front of positive numbers Left or right justifying numbers in a given space Slide 6-
  • 38. Formatting Output to Files Format output to the screen with: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Format output to a file using the out-file stream named out_stream with: out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); Slide 6-
  • 39. out_stream.precision(2); precision is a member function of output streams After out_stream.precision(2); Output of numbers with decimal points… will show a total of 2 significant digits 23. 2.2e7 2.2 6.9e-1 0.00069 OR will show 2 digits after the decimal point 23.56 2.26e7 2.21 0.69 0.69e-4 Calls to precision apply only to the stream named in the call Slide 6-
  • 40. setf(ios::fixed); setf is a member function of output streams setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag After out_stream.setf(ios::fixed); All further output of floating point numbers… Will be written in fixed-point notation, the way we normally expect to see numbers Calls to setf apply only to the stream named in the call Slide 6-
  • 41. After out_stream.setf(ios::showpoint); Output of floating point numbers… Will show the decimal point even if all digits after the decimal point are zeroes setf(ios::showpoint); Slide 6- Display 6.5
  • 42. Creating Space in Output The width function specifies the number of spaces for the next item Applies only to the next item of output Example: To print the digit 7 in four spaces use out_stream.width(4); out_stream << 7 << endl; Three of the spaces will be blank Slide 6- (ios::right) (ios::left) 7 7
  • 43. Not Enough Width? What if the argument for width is too small? Such as specifying cout.width(3); when the value to print is 3456.45 The entire item is always output If too few spaces are specified, as many more spaces as needed are used Slide 6-
  • 44. Unsetting Flags Any flag that is set, may be unset Use the unsetf function Example: cout.unsetf(ios::showpos); causes the program to stop printing plus signs on positive numbers Slide 6-
  • 45. Manipulators A manipulator is a function called in a nontraditional way Manipulators in turn call member functions Manipulators may or may not have arguments Used after the insertion operator (<<) as if the manipulator function call is an output item Slide 6-
  • 46. The setw Manipulator setw does the same task as the member function width setw calls the width function to set spaces for output Example: cout << &quot;Start&quot; << setw(4) << 10 << setw(4) << setw(6) << 30; produces: Start 10 20 30 Slide 6- Two Spaces Four Spaces
  • 47. The setprecision Manipulator setprecision does the same task as the member function precision Example: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << &quot;$&quot; << setprecision(2) << 10.3 << endl << &quot;$&quot; << 20.5 << endl; produces: $10.30 $20.50 setprecision setting stays in effect until changed Slide 6-
  • 48. Manipulator Definitions The manipulators setw and setprecision are defined in the iomanip library To use these manipulators, add these lines #include <iomanip> using namespace std; Slide 6-
  • 49. Stream Names as Arguments Streams can be arguments to a function The function's formal parameter for the stream must be call-by-reference Example: void make_neat(ifstream& messy_file, ofstream& neat_file); Slide 6-
  • 50. The End of The File Input files used by a program may vary in length Programs may not be able to assume the number of items in the file A way to know the end of the file is reached: The boolean expression (in_stream >> next) Reads a value from in_stream and stores it in next True if a value can be read and stored in next False if there is not a value to be read (the end of the file) Slide 6-
  • 51. End of File Example To calculate the average of the numbers in a file double next, sum = 0; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } double average = sum / count; Slide 6-
  • 52. Stream Arguments and Namespaces Using directives have been local to function definitions in the examples so far When parameter type names are in a namespace A using directive must be outside the function so C++ will understand the parameter type names such as ifstream Easy solution is to place the using directive at the beginning of the file Many experts do not approve as this does not allow using multiple namespaces with names in common Slide 6-
  • 53. The program in Display 6.6… Takes input from rawdata.dat Writes output to the screen and to neat.dat Formatting instructions are used to create a neater layout Numbers are written one per line in a field width of 12 Each number is written with 5 digits after the decimal point Each number is written with a plus or minus sign Uses function make_neat that has formal parameters for the input-file stream and output-file stream Program Example Slide 6- Display 6.6 (1) Display 6.6 (2) Display 6.6 (3)
  • 54. Section 6.2 Conclusion Can you Show the output produced when the following line is executed? cout << &quot;*&quot; << setw(3) << 12345 << &quot;*&quot; endl; Describe the effect of each of these flags? Ios::fixed ios::scientific ios::showpoint ios::right ios::right ios::showpos Slide 6-
  • 55. 6.3 Character I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 56. Character I/O All data is input and output as characters Output of the number 10 is two characters '1' and '0' Input of the number 10 is also done as '1' and '0' Interpretation of 10 as the number 10 or as characters depends on the program Conversion between characters and numbers is usually automatic Slide 6-
  • 57. Low Level Character I/O Low level C++ functions for character I/O Perform character input and output Do not perform automatic conversions Allow you to do input and output in anyway you can devise Slide 6-
  • 58. Member Function get Function get Member function of every input stream Reads one character from an input stream Stores the character read in a variable of type char, the single argument the function takes Does not use the extraction operator (>>) which performs some automatic work Does not skip blanks Slide 6-
  • 59. Using get These lines use get to read a character and store it in the variable next_symbol char next_symbol; cin.get(next_symbol); Any character will be read with these statements Blank spaces too! '\n' too! (The newline character) Slide 6-
  • 60. get Syntax input_stream.get(char_variable); Examples: char next_symbol; cin.get(next_symbol); ifstream in_stream; in_stream.open(&quot;infile.dat&quot;); in_stream.get(next_symbol); Slide 6-
  • 61. More About get Given this code: char c1, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); and this input: AB CD c1 = 'A' c2 = 'B' c3 = '\n' cin >> c1 >> c2 >> c3; would place 'C' in c3 (the &quot;>>&quot; operator skips the newline character) Slide 6-
  • 62. The End of The Line To read and echo a line of input Look for '\n' at the end of the input line: cout<<&quot;Enter a line of input and I will &quot; << &quot;echo it.\n&quot;; char symbol; do { cin.get(symbol); cout << symbol; } while (symbol != '\n'); All characters, including '\n' will be output Slide 6-
  • 63. '\n ' vs &quot;\n &quot; '\n' A value of type char Can be stored in a variable of type char &quot;\n&quot; A string containing only one character Cannot be stored in a variable of type char In a cout-statement they produce the same result Slide 6-
  • 64. Member Function put Function put Member function of every output stream Requires one argument of type char Places its argument of type char in the output stream Does not do allow you to do more than previous output with the insertion operator and cout Slide 6-
  • 65. put Syntax Output_stream.put(Char_expression); Examples: cout.put(next_symbol); cout.put('a'); ofstream out_stream; out_stream.open(&quot;outfile.dat&quot;); out_stream.put('Z'); Slide 6-
  • 66. Member Function putback The putback member function places a character in the input stream putback is a member function of every input stream Useful when input continues until a specific character is read, but you do not want to process the character Places its argument of type char in the input stream Character placed in the stream does not have to be a character read from the stream Slide 6-
  • 67. putback Example The following code reads up to the first blank in the input stream fin, and writes the characters to the file connected to the output stream fout fin.get(next); while (next != ' ') { fout.put(next); fin.get(next); } fin.putback(next); The blank space read to end the loop is put back into the input stream Slide 6-
  • 68. Program Example Checking Input Incorrect input can produce worthless output Use input functions that allow the user to re-enter input until it is correct, such as Echoing the input and asking the user if it is correct If the input is not correct, allow the user to enter the data again Slide 6-
  • 69. Checking Input: get_int The get_int function seen in Display 6.7 obtains an integer value from the user get_int prompts the user, reads the input, and displays the input After displaying the input, get_int asks the user to confirm the number and reads the user's response using a variable of type character The process is repeated until the user indicates with a 'Y' or 'y' that the number entered is correct Slide 6-
  • 70. The new_line function seen in Display 6.7 is called by the get_int function new_line reads all the characters remaining in the input line but does nothing with them, essentially discarding them new_line is used to discard what follows the first character of the the user's response to get_line's &quot;Is that correct? (yes/no)&quot; The newline character is discarded as well Checking Input: new_line Slide 6- Display 6.7 (1) Display 6.7 (2)
  • 71. Checking Input: Check for Yes or No? get_int continues to ask for a number until the user responds 'Y' or 'y' using the do-while loop do { // the loop body } while ((ans !='Y') &&(ans != 'y') ) Why not use ((ans =='N') | | (ans == 'n') )? User must enter a correct response to continue a loop tested with ((ans =='N') | | (ans == 'n') ) What if they mis-typed &quot;Bo&quot; instead of &quot;No&quot;? User must enter a correct response to end the loop tested with ((ans !='Y') &&(ans != 'y') ) Slide 6-
  • 72. Mixing cin >> and cin.get Be sure to deal with the '\n' that ends each input line if using cin >> and cin.get &quot;cin >>&quot; reads up to the '\n' The '\n' remains in the input stream Using cin.get next will read the '\n' The new_line function from Display 6.7 can be used to clear the '\n' Slide 6-
  • 73. '\n' Example The Code: cout << &quot;Enter a number:\n&quot;; int number; cin >> number; cout << &quot;Now enter a letter:\n&quot;; char symbol; cin.get(symbol); Slide 6- The Dialogue: Enter a number: 21 Now enter a letter: A The Result: number = 21 symbol = '\n'
  • 74. A Fix To Remove '\n' cout << &quot;Enter a number:\n&quot;; int number; cin >> number; cout << &quot;Now enter a letter:\n&quot;; char symbol; cin >>symbol; Slide 6-
  • 75. Another '\n' Fix cout << &quot;Enter a number:\n&quot;; int number; cin >> number; new_line( ); // From Display 6.7 cout << &quot;Now enter a letter:\n&quot;; char symbol; cin.get(symbol); Slide 6-
  • 76. Detecting the End of a File Member function eof detects the end of a file Member function of every input-file stream eof stands for end of file eof returns a boolean value True when the end of the file has been reached False when there is more data to read Normally used to determine when we are NOT at the end of the file Example: if ( ! in_stream.eof( ) ) Slide 6-
  • 77. Using eof This loop reads each character, and writes it to the screen in_stream.get(next); while (! in_stream.eof( ) ) { cout << next; in_stream.get(next); } ( ! In_stream.eof( ) ) becomes false when the program reads past the last character in the file Slide 6-
  • 78. The End Of File Character End of a file is indicated by a special character in_stream.eof( ) is still true after the last character of data is read in_stream.eof( ) becomes false when the special end of file character is read Slide 6-
  • 79. How To Test End of File We have seen two methods while ( in_stream >> next) while ( ! in_stream.eof( ) ) Which should be used? In general, use eof when input is treated as text and using a member function get to read input In general, use the extraction operator method when processing numeric data Slide 6-
  • 80. The program of Display 6.8… Reads every character of file cad.dat and copies it to file cplusad.dat except that every 'C' is changed to &quot;C++&quot; in cplusad.dat Preserves line breaks in cad.dat get is used for input as the extraction operator would skip line breaks get is used to preserve spaces as well Uses eof to test for end of file Program Example: Editing a Text File Slide 6- Display 6.8 (1) Display 6.8 (2)
  • 81. Character Functions Several predefined functions exist to facilitate working with characters The cctype library is required #include <cctype> using namespace std; Slide 6-
  • 82. The toupper Function toupper returns the argument's upper case character toupper('a') returns 'A' toupper('A') return 'A' Slide 6-
  • 83. toupper Returns An int Characters are actually stored as an integer assigned to the character toupper and tolower actually return the integer representing the character cout << toupper('a'); //prints the integer for 'A' char c = toupper('a'); //places the integer for 'A' in c cout << c; //prints 'A' cout << static_cast<char>(toupper('a')); //works too Slide 6-
  • 84. isspace returns true if the argument is whitespace Whitespace is spaces, tabs, and newlines isspace(' ') returns true Example: if (isspace(next) ) cout << '-'; else cout << next; Prints a '-' if next contains a space, tab, or newline character See more character functions in The isspace Function Slide 6- Display 6.9 (1) Display 6.9 (2)
  • 85. Section 6.3 Conclusion Can you Write code that will read a line of text and echo the line with all the uppercase letters deleted? Describe two methods to detect the end of an input file: Describe whitespace? Slide 6-
  • 86. Chapter 6 -- End Slide 6-
  • 87. Display 6.1 Slide 6- Back Next
  • 88. Display 6.2 Slide 6- Back Next
  • 89. Display 6.3 Slide 6- Back Next
  • 90. Display 6.4 (1/2) Slide 6- Back Next
  • 91. Display 6.4 (2/2) Slide 6- Back Next
  • 92. Display 6.5 Slide 6- Back Next
  • 93. Display 6.6 (1/3) Slide 6- Back Next
  • 94. Display 6.6 (2/3) Slide 6- Back Next
  • 95. Display 6.6 (3/3) Slide 6- Back Next
  • 96. Display 6.7 (1/2) Slide 6- Back Next
  • 97. Display 6.7 (2/2) Slide 6- Back Next
  • 98. Display 6.8 (1/2) Slide 6- Next Back
  • 99. Display 6.8 (2/2) Slide 6- Back Next
  • 100. Display 6.9 (1/2) Slide 6- Back Next
  • 101. Display 6.9 (2/2) Slide 6- Back Next