cmsc 2021 c++ i/o and other topics. cmsc 2022 using c++ stream i/o default input stream is called...

22
CMSC 202 1 C++ I/O and Other Topics

Upload: garey-baldwin

Post on 17-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

CMSC 202 1

C++ I/O and Other Topics

CMSC 202 2

Using C++ Stream I/O

• Default input stream is called cin

• Default output stream is called cout

• Use the extraction operator >> with cin

• Use the insertion operator << with cout

• We will see later that cin and cout are actually objects

CMSC 202 3

Using cin• integers and floats

cin >> i1 >> f1; // skips over whitespace

• characters

cin >> ch1 >> ch2; // skips over whitespace

To not skip whitespace, use cin.get:

ch = cin.get(); // reads any character

CMSC 202 4

Using cin (con’t)• strings (char*)

cin >> str; // reads until first whitespace

Better to use cin.getline:

cin.getline(str, buffer_size, end_char);

where buffer_size = size of str, including ‘\0’

end_char = character to stop at

Reading stops when end_char is encountered, the end-of-file is encountered, or when buffer_size-1 has been exceeded. ‘\n’ is the default for end_char. Automatically appends ‘\n’ to the string.

CMSC 202 5

Using cout

• integers and floats

cout << i1 << f1; // displayed in default format

• characters

cout << ch; // single character displayed

• strings (char*)

cout << str; // displays up to ‘\0’ character

CMSC 202 6

General File I/O Steps

• Declare a file name variable

• Associate the file name variable with the disk file name

• Open the file

• Use the file

• Close the file

CMSC 202 7

C++ File I/O

• Declare a file name variable

#include <fstream.h>

ifstream input_filename_var; // input file

ofstream output_filename_var; // output file

CMSC 202 8

C++ File I/O (con’t)

• Associate the file name variable with the disk file name and open it

input_filename_var.open(“pathname/filename”, ios::in);

output_filename_var.open(“pathname/filename”, ios::out);

where ios::in and ios::out are optional

Files may be opened in other modes such as ios::app (append) and ios::binary (binary input or output)

CMSC 202 9

C++ File I/O (con’t)

File name declaration and opening/association may be combined:

ifstream input_filename_var(pathname/filename, ios::in);

ofstream input_filename_var(pathname/filename, ios::out);

where ios::in and ios::out are optional

CMSC 202 10

C++ File I/O (con’t)• Use the file

• Use an input file as you would use the cin input stream

ifile1 >> x >> y; // x and y are integers

ifile2 >> ch; // ch is a char

ch = ifile3.get(); // ch is a char

ifile4.getline(buffer, buffer_size) // buffer is char*

CMSC 202 11

C++ File I/O (con’t)

• Use an output file as you would use the cout output stream

ofile1 << x << y; // x and y are integers

ofile2 << ch; // ch is a char

ofile3 << “Hi there!” << endl; // literal string

ofile4 << str; // str is a char*

CMSC 202 12

C++ File I/O (con’t)

• Close the file

input_filename_var.close();

output_filename_var.close();

All files are closed automatically upon termination of program execution, but it is a good habit to close them explicitly. Also, close them as soon as they are no longer needed by the program.

CMSC 202 13

Checking That Files Have Opened Successfully

• Always check that all files (input or output) have been successfully opened

• If any file cannot be opened, send a message to the user and terminate program execution

ifstream myFile(“inputData”);

if (!myFile) {

cerr << “Input file could not be opened” << endl;

exit(1); // must #include <stdlib.h> to use exit function

}

CMSC 202 14

Checking for End-of-Fileifstream inFile(“somefile.txt”);

. . .

if (inFile) . . . OR while (inFile) . . .

Checks to see if the last operation on inFile was successful. If yes, then the condition is true; otherwise, it is false.

So, if the last operation was a read, then you are checking to see if the end-of-file has been reached.

CMSC 202 15

Sample Program Using File I/O#include <fstream.h>

#include <iostream.h>

#include <stdlib.h>

void main() {

ifstream inFile(“numbers.dat”);

int x;

if (!inFile) {

cerr << “Cannot open input file. Exiting.” << endl;

exit(1);

}

CMSC 202 16

Sample Program (con’t)

inFile >> x;

while (inFile) { // OR while (inFile >> x) and

inFile >> x; // omit the priming read

cout << x << endl;

}

inFile.close();

}

CMSC 202 17

Passing by ReferenceIn C:

swap(&x, &y); // call passes addresses

void swap(int* x, int* y) { // ptrs receive addresses

int temp;

temp = *x; // dereference pointer

*x = *y; // dereference pointers

*y = temp; // dereference pointer

}

CMSC 202 18

Passing by Reference (con’t)In C++:

swap(x, y); // just pass variable

void swap(int& x, int&y) { // x and y are references

int temp;

temp = x; // no dereferencing

x = y; // no dereferencing

y = temp; // no dereferencing

}

CMSC 202 19

Constants#define PI 3.14

Preprocessor replaces all occurrences of PI with the value 3.14. #define actually defines a macro.

const int PI = 3.14;

Is not replaced by the processor. Value cannot be changed -- runtime error.

CMSC 202 20

Other C++ Topics

• Can us endl in place of ‘\n’

• Variables can be declared anywhere in C++ code (but pick a logical place)

• Output can be formatted by using stream manipulators (e.g., setw, setprecision) (Ch. 11.6)

• Namespaces - now part of ANSI C++ (Ch. 21)

CMSC 202 21

Other Things to be Aware of (both C and C++)

• in-line functions

• avoids a function call by “advising” the compiler to generate a copy of the function in place of each call

• faster execution, but larger object file

inline float area(int h, int w) { return h * w}

int main() . . .

CMSC 202 22

Other Things to be Aware of (both C and C++) (con’t)

• static storage class

• scope

• block

• function

• file

• class (C++ only)