Presentation is loading. Please wait.

Presentation is loading. Please wait.

I/O Streams as an Introduction to Objects and Classes

Similar presentations


Presentation on theme: "I/O Streams as an Introduction to Objects and Classes"— Presentation transcript:

1 I/O Streams as an Introduction to Objects and Classes
Chapter 6 I/O Streams as an Introduction to Objects and Classes

2 Stream is a flow of information is a C++ object.
There are 2 types of stream Standard stream (cin, cout) File stream (ifstream, ofstream)

3 File Stream and File Handler
Used to read from/write to a file. Library: fstream #include <fstream> Declaration: to create a file stream object. Create an input file stream object (input file handler) Syntax: ifstream name; Ex: ifstream inStream; Create an output file stream object (output file handler) Syntax: ofstream name; Ex: ofstream outStream;

4 File Open Open the files: connect file handler to external file
Open input file: only used with ifstream variables and for reading only. Nothing will change to the file. Ex: Connect inStream to the actual file named inFile.dat inStream.open(“inFile.dat”); Open output file: only used with ofstream variables for writing. Ex: Create an external output file outFile.dat (if not exists) and connect outStream to it. Start with a blank file. outStream.open(“outFile.dat”); Ex: Create an external output file outFile.dat (if not exists) and connect outStream to it. Start at the end of the current file. outStream.open(“outFile.dat”, ios::app); Logical Name Physical Name

5 File Name Absolute path: The full path of a file
inStream.open(“C:/Temp/inFile.dat”); Relative path: where the file is, based on the current location of the executable file. In the same location: inStream.open(“inFile.dat”); In the 1 level upper: inStream.open(“../inFile.dat”); In another same level directory: inStream.open(“../input/inFile.dat”); Can get from user, using c-string variable: char fileName[20]; cin >> fileName; inStream.open(fileName);

6 Check for File Open Check if a file is opened successfully: Ex:
inStream.fail(); // Failed if no file named inFile.dat exists outStream.fail(); // Failed if no room on disk or someone is using outFile.dat Ex: inStream.open(“inFile.dat”); if (inStream.fail()) { cout << “Input file opening failed.\n”; exit(1); } Function exit(n) is in the library <cstdlib>. It is used to exit the program. Remember to close all of the currently opened file before calling exit().

7 Close File To disconnect the file handler from the actual external file. Ex: inStream.close(); outStream.close();

8 File I/O Example outStream.open(outFileName);
if (outStream.fail()) { cout << "Output file opening failed. \n" ; exit (1); } int first, second, third; instream >> first >> second >> third; outStream << "The sum of the first 3 numbers in "; outStream << outFileName << " is: "; outStream << (first + second + third) << endl; inStream.close(); outStream.close(); cout << “End of Program. \n”; return 0; #include <fstream> #include <iostream> #include <cstdlib> using namespace std; int main () { char inFileName[20], outFileName[20]; ifstream inStream; ofstream outStream; cout << "Sum up 3 numbers taken from an input file \n"; cout << "And write the sum to the output file. \n"; cout << "Enter the input file name: "; cin >> inFileName; cout << "Enter the output file name: "; cin >> outFileName; inStream.open(inFileName); if (inStream.fail()) cout << "Input file opening failed. \n" ; exit (1); }

9 File I/O Example (cont.)
Sum up 3 numbers taken from an input file And write the sum to the output file. Enter the input file name: numbers.dat Enter the output file name: output.dat End of Program. Output to the screen 1 2 3 4 numbers.dat The sum of the first 3 numbers in numbers.dat is: 6 output.dat

10 File I/O Example outStream.open(outFileName);
if (outStream.fail()) { cout << "Output file opening failed. \n" ; exit (1); } string first, second, third; instream >> first >> second >> third; outStream << "The first 3 strings from "; outStream << outFileName << " in backward order are: "; outStream << third << endl; outStream << second << endl; outStream << first << endl; inStream.close(); outStream.close(); cout << “End of Program. \n”; return 0; #include <fstream> #include <iostream> #include <cstdlib> using namespace std; int main () { char inFileName[20], outFileName[20]; ifstream inStream; ofstream outStream; cout << “Get the first 3 strings from an input file \n"; cout << "And write them backward to the output file. \n"; cout << "Enter the input file name: "; cin >> inFileName; cout << "Enter the output file name: "; cin >> outFileName; inStream.open(inFileName); if (inStream.fail()) cout << "Input file opening failed. \n" ; exit (1); }

11 File I/O Example (cont.)
Get the first 3 strings from an input file And write them backward to the output file. Enter the input file name: numbers.dat Enter the output file name: output.dat End of Program. Output to the screen 1 2 3 4 numbers.dat The first 3 strings from numbers.dat in backward order are: 3 2 1 output.dat

12 Format File Outputs with Flags
File Output Formatting with: ofstream outStream; Standard Output Formatting cout.setf (ios::fixed); cout.setf (ios::showpoint); cout.precision(2); outStream.setf (ios::fixed); outStream.setf(ios::showpoint); outStream.precision(2);

13 Class operators Scope resolution operator: :: - connects the value or function on the right to the context (class, namespace) on the left. Dot operator: . – connects the function on the right to the class object (the variable of a class) on the left.

14 Set flag (fixed and scientific)
precision(n): determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) ios::fixed: When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part. ios::scientific: When floatfield is set to scientific, floating-point values are written using scientific notation: the value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter e followed by an optional sign and three exponential digits.

15 Set flag example (fixed and scientific)
default: 3.1416 2006 1e-010 fixed: scientific: e e e-010 #include <iostream> using namespace std; int main () { double a = ; double b = ; double c = 1.0e-10; cout.precision(5); cout << "default:\n"; cout << a << endl << b << endl << c << endl << endl; cout.setf (ios::fixed); cout << "fixed:\n"; cout.setf (ios::scientific); cout << "scientific:\n" << std::scientific; return 0; }

16 Set flag (showpoint) ios::showpoint: When the showpoint format flag is set, the decimal point is always written for floating point values inserted into the stream (even for those whose decimal part is zero). Following the decimal point, as many digits as necessary are written to match the precision set for the stream. #include <iostream> // std::cout, std::showpoint, std::noshowpoint using namespace std; int main () { double a = 30; double b = ; double pi = ; cout.setf (ios::showpoint); cout << a << '\t' << b << '\t' << pi << '\n'; std::cout.precision (5); cout.setf (ios::fixed); return 0; } Output:

17 Set flag (width, showpos, left and right)
ios::width: sets a new field width for the stream. The field width determines the minimum number of characters to be written in some output representations. If the standard width of the representation is shorter than the field width, the representation is padded with fill characters at a point determined by the format flag adjustfield (one of left, right or internal) ios::showpos: When the showpos format flag is set, a plus sign (+) precedes every non-negative numerical value inserted into the stream (including zeros). ios::left: When adjustfield is set to left, the output is padded to the field width (width) by inserting fill characters (fill) at the end, effectively adjusting the field to the left. ios::right: When adjustfield is set to right, the output is padded to the field width (width) by inserting fill characters (fill) at the beginning, effectively adjusting the field to the right.

18 Set flag example (width, showpos, left and right)
#include <iostream> using namespace std; int main () double n = -77.5, m = 82.7, l=0; cout.setf(ios::left); cout << "Left:" << endl; cout.width(6); cout << n << endl; cout << m << endl << endl; cout.setf(ios::right); cout << "Right:" << endl; cout.setf(ios::showpos); cout << "Show positive:" << endl; cout << m << endl; cout << l << endl; return 0; } Left: -77.5 82.7 Right: Show positive: +82.7 +0

19 setw(n) and setprecision(n) manipulators
manipulators: change the manner of the output stream. inserted directly in the output stream. #include <iomanip> setw(n): sets width of field for next variable. As same at width(n) setprecision(n): sets number of decimal. As same as precision(n) Examples: cout << setw(5) << 123; // bb123 cout << setprecision(10) << 123.4; //

20 Character I/O cin.get(ch) - reads one character at a time and stores it in ch. Does not skip blanks or non-printable characters. cout.put(ch) - puts ch to the screen. #include <iostream> or <fstream> (if used on file only)

21 Character I/O (cont.) char ch; do { cin.get (ch); cout<< ch;
} while (ch != ‘\n’); char ch; do { cin>>ch; cout<< ch; } while (ch != ‘\n’) Will display all characters Will stop at end of line Will only display printable characters Infinite loop since it doesn’t “read” whitespace

22 Predefined Character functions
toupper(ch) tolower(ch) isupper(ch) islower(ch) isalpha(ch) isdigit(ch) isalnum(ch) isspace(ch)

23 End-Of-File (eof) eof() is an member function of ifstream class.
It is used to determine when all the file has been read and there is no more input left. Ex: ifstream inStream; instream.open (“numbers.dat”); int x; inStream >> x; while (!inStream.eof()) { cout << x << endl; }

24 Default Arguments for Functions
The declaration of the function open is: void open ( const char * filename, ios_base::openmode mode = ios_base::out ); Uses of function open: outStream.open(“outFile.dat”, ios::app); // Open file to append outStream.open(“outFile.dat”, ios::out); // Open file to output However, the default value for parameter mode is set to ios_base::out. So, only need to pass the argument if it is not ios_base::out. outStream.open(“outFile.dat”); // Open file to output Note: The default argument is always at the end of the parameter list.

25 Default Arguments for Functions (Example)
int sum (int n1, int n2=5, int n3 =10) { return (n1+n2+n3); } What are the values of x’s: int x = sum (2); int x = sum (4, 7); int x = sum (9, 3, 8); 2+5+10=17 4+7+10=21 9+3+8=20


Download ppt "I/O Streams as an Introduction to Objects and Classes"

Similar presentations


Ads by Google