0% found this document useful (0 votes)
76 views19 pages

C++ Ders7 - Streams

The document discusses input/output (I/O) streams in C++. It defines streams as sequences of characters that flow between I/O devices and programs. The standard input stream is cin, which represents keyboard input, and the standard output stream is cout, which represents monitor output. File streams can also be used to read from and write to files. Common operators like >> and << are used to extract and insert data to and from streams.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views19 pages

C++ Ders7 - Streams

The document discusses input/output (I/O) streams in C++. It defines streams as sequences of characters that flow between I/O devices and programs. The standard input stream is cin, which represents keyboard input, and the standard output stream is cout, which represents monitor output. File streams can also be used to read from and write to files. Common operators like >> and << are used to extract and insert data to and from streams.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Whats an I/O (Input/Output) Stream?

 A sequence of characters flowing between the I/O devices

and programs

 therefore it is a buffer area for I/O

 We extract and insert using >> and << operators respectively


 cin is the standard input stream (i.e. keyboard)
Ali Veli 45 Ahmet cs201 >>

 cout is the standard output stream (i.e. monitor)


John George 3 Mike Joe

<<

 We also have file streams (for file I/O) that we will see later

Streams for reading and writing files


 Weve seen the standard input stream cin, and the standard

output stream cout


 For reading from the keyboard, writing to the screen
 Accessible from <iostream>

 Other streams let us read from files and write to files


 Why do we need such a file I/O?
 Because files are permanently stored; whereas the keyboard entry is
for one time and screen output is volatile
 We can input the same data several times if we use file input


Or we can modify the input file and re-run program using the modified data

 We can save the output for future reference

Streams for reading and writing files


 syntax for reading and writing is similar to cin and

cout, because they are all streams


 To use a file stream, it must be opened first
 Opening binds the stream variable to a physical file
 After opening, I/O to/from this file can be performed.
 Should close file streams, but happens automatically for

input streams when the program finishes.


 We need to close output streams as will be discussed later

 cin and cout are not opened and closed, because they

are standard streams and compiler knows how to handle


them
 Input files are generally text files that can easily be

generated using Notepad.

Input file stream: Note similarity to cin


counting words
from keyboard

string word;
int numWords = 0;
// # words read so far
while (cin >> word)
// while read succeeded read and
{
numWords++;
// count
}
cout << "number of words read = " << numWords << endl;

counting words of a file

string word;
int numWords = 0;
ifstream input;
string filename;

// defining input file stream

cin >> filename;


input.open(filename.c_str());

// input the file name


// open the file

while (input >> word) // while read succeeded from file


{
numWords++;
}
cout << "number of words read = " << numWords << endl;
 See countw.cpp

Counting words in a file


 See countw2.cpp
 Idea is in the previous slide
 Enhancement: also finds the average word length
 add the word lengths up and at the end divide it by the

word count
 Study for yourselves
 find the largest and smallest word in a file

Example (not in book)


 Find the longest word (max number of characters) in a file.
 Idea for algorithm/program
 Read every word, remember the longest word read so far
 Each time a word is read, compare to longest-so-far. If longer, then
theres a new longest-so-far

 See longestword.cpp (not in book)


 why did we initialize maxlength to 0?
 zero is the minimum possible word length
 initialization to any negative value would also work
 what happens if there are more than one words with the

same max length in the file?


 finds the first one (finding all either requires processing the same file

twice or requires some other tools that we will learn in a few weeks)

Example (not in book)


 Count the total number of integers in a file that may also

contain non-integer values


 If you encounter a non-integer data in the file, skip it and

continue until the end of the file


 We have to check the end of file using eof function
 because extraction ( >> operator) returns false both when

end-of-file is reached and when the input is not an integer


 we have to differentiate between these two cases
 loop control is until the eof
 inside loop, check if the input is successful and count accordingly

 lets see countintegers.cpp (not in the book)

More on file/stream input


 There is an abstract pointer that shows the next input to

read
 when a file is opened, this pointer shows the first character
 when read, it moves towards the end of file sequentially

 it is possible to move that pointer using

ifstream::seekg(n)member function where


n is the position to be moved.
 seekg(0) moves to the beginning of the file necessary

to process the same file more than once


 For this course it is sufficient to use seekg(0) when
necessary, but later you may need to use seekg with
nonzero arguments for more sophisticated file processing
applications

Example (not in book)


 Example: calculate average word length of a file and

find the total number of words that have more than


average word length characters
 we need two passes over the same file
 one for average, one for number of words longer than the average
 see longerwords.cpp (not in the book)

 Two important tips


 always pass a file stream to a function as a reference

parameter
 use clear before calling seekg

ofstream: Output file stream


 We can also use files for output
 ofstream class
 use is similar to cout
 first open the file (as in ifstream)
 then use << operator to write into output file stream
 better if you close the file using close() member function (to be on
the safe side, close all output files when done)
 #include <fstream> is needed (as in ifstream)
 When opened, the previous content of the file is automatically

deleted.
 To append to the end of an output file without deleting the
previous content, use ios::app as the second argument of
open
 Example (not in book)
 write a program to create a file and fill that file with 10 random numbers

(between 1 and 100). One number per line.


 see outfile.cpp

String Utility Functions - Revisited


 Free functions defined in strutils.h (Tapestry Utilities)
 should include strutils.h at the beginning of the program
 should add strutils.cpp to the project
 some functions are the following (refer to above files for the full list)
ToLower
ToUpper
StripPunc
tostring
atoi
itoa

return a lowercase version of a string


return an uppercase version of a string
remove leading/trailing punctuation
int-to-string conversion (e.g. return "123" for 123)
string-to-int conversion (e.g. returns 123 for "123")
same as tostring

 Used some of them before and may need later

input using getline


 getline is a free function to read a full line from input

stream
 input stream can be a file or cin

>> operator reads one by one


 blanks are delimiter

getline reads whole line and stores in its string parameter


 Syntax

getline(input stream, string variable)


 getline also returns a boolean value
 true if input successful
 false if unsuccessful
 used in loops to process until the end of file

Example (See filelines.cpp)


 Count number of lines and number of characters of a file
ifstream input;
string s;
int numLines = 0;
int numChars = 0;
string filename = PromptString("enter name of input file: ");
input.open(filename.c_str());
if (input.fail() )
{
cout << "could not open file " << filename << endl;
return 0;
}
read one line and check if
input is successfully read
while (getline(input, s))
(i.e. not at the end of file
{
numLines++;
numChars += s.length();
}
cout << "number of lines = " << numLines
<< ", number of characters = " << numChars << endl;

Using getline on cin


 You can read a line of data from keyboard

string s;
getline(cin,s);

// gets the whole line into s

 discard the rest of a line after reading the input


int num;
cin >> num;
getline(cin, s);

// input
// discard the rest of the line
// by reading in a dummy string

 You will need an extra empty line in the input (i.e. press the

enter key twice) in Windows


 Only when you use getline for cin, not for getline for files

Input using get


 get is a member function for ifstream
 reads one character into its char argument
 does not skip blanks and control characters
 read them as characters

 Example: similar example as before


 counts lines and characters of a file
 but also counts blanks (not in the book)

 See filelines2.cpp and next slide for the code

int numChars = 0;
int numLines = 0;
int numBlanks = 0;
char ch;
// be careful about the type char
string filename = PromptString("enter name of input file: ");
ifstream input;
input.open(filename.c_str());
if (input.fail() )
{
cout << "could not open file " << filename << endl;
return 0;
while next character is read
}
successfully
(i.e. end of file is not reached)
while (input.get(ch))
{
numChars++;
if ('\n' == ch)
if character is a newline character,
increment
{
numLines++;
increment line counter
character
}
counter
else if (' ' == ch)
{
numBlanks++;
if character is a blank,
}
increment blank counter
}
cout << "number of lines = " << numLines << endl
<< "number of characters = " << numChars << endl
<< "number of blanks = " << numBlanks <<endl;

Input String Stream


 In files, data are generally line oriented (easier to

understand for human beings)


 Example (student name, lastname and grades,

one line per student)


John Ozcalisir 100 100 100 100
Bill Yatar 12 40
Alice Idareeder 50 55 46
 Problem: We have to process the data line by line, but we do

not know how many grades we have in one line


 Reading using >> does not help since we miss end of line

 Solution: Read data line by line (using getline) into a string

variable and then parse each line


 We need a tool that allows us to use >> on strings in order to extract

data out of each line


 This tool is called input string stream

Input String Stream parselines.cpp


...

while (getline(ifile,s))
{
total = 0; count = 0;
istringstream input(s);
input >> name >> lastname;

Read one line at each iteration


Create an input string stream out
of the current line

Read two strings from current


while (input >> num)
line
{
count++;
total += num;
Read numbers until the end of
}
line
if (count != 0)
{
cout <<name<<" "<<lastname<<": average of "<<
count<<" grades = " << double(total)/count << endl;
}
else
{
cout << "wrong or no input!" << endl;
}
}

Input String Stream Details and Tips


 istringstream is a class defined in sstream

header file
 You have to #include <sstream>
 No cpp necessary (standard class)

 istringstream object must be created by

passing the source string as an argument


 See previous example
 You cannot later change the source string
 That is why we have created a new istringstream object for each
line (THIS IS VERY IMPORTANT).

 We also have output string stream

You might also like