C++ Ders7 - Streams
C++ Ders7 - Streams
and programs
<<
We also have file streams (for file I/O) that we will see later
Or we can modify the input file and re-run program using the modified data
cin and cout are not opened and closed, because they
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;
string word;
int numWords = 0;
ifstream input;
string filename;
word count
Study for yourselves
find the largest and smallest word in a file
twice or requires some other tools that we will learn in a few weeks)
read
when a file is opened, this pointer shows the first character
when read, it moves towards the end of file sequentially
parameter
use clear before calling seekg
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
stream
input stream can be a file or cin
string s;
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
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;
while (getline(ifile,s))
{
total = 0; count = 0;
istringstream input(s);
input >> name >> lastname;
header file
You have to #include <sstream>
No cpp necessary (standard class)