Transcript streams4.2B
Start
File Streams
03/04/11
Stream as Connection to I/O
Example of Creating a Stream
Program
that outputs a quote to a file
writefile.cpp
To Connect Stream to File
•
Header File
#include <fstream>
•
Declare stream & open file
ifstream fs_in(“mydata”, ios::in);
ofstream fs_out(“myout”, ios::out);
To Connect Stream to File
3. Input/Output
fs_in >> x;
fs_out << “Hello>\n”;
4. Close
fs_in.close( );
fs_out.close( );
Example of Input
Write
a program to input a list of positive
numbers from a file, then output the sum.
– Create stream and connect to file.
– Input number from input stream
– While number not negative
– Add number to sum
– Input number from input stream
– Output sum
– Close stream
streams4.2/sum.cpp
Another Problem
Start Here
Write
a program to input a file of five
temperatures in degrees Celsius. Convert
the temperatures to Fahrenheit and output
them to another file. Use a function to do
the conversion.
What would the algorithm be?
Let's write the program.(f = 9/5c + 32)
celsius.txt
Sentinel Data in a File
Value
that is not part of the data marks the
end of a list.
I am going to use '*' as a sentinal to mark
the end of data in some character input in
the next example.
Caesar Cipher
Using
the Caesar Shift (2 to the right), the
message.
"RETURN TO ROME"
would be encrypted as,
"TGVWTP VQ TQOG"
Essentially, add +2 to the ascii value of a
character.
To decode shift it back by -2
Caesar Cipher
When
using cin with characters, spaces are
skipped.
cin.get() inputs the spaces, too.
Caesar Cipher
Write
a program that inputs a message
from the keyboard and saves the coded
version in a file called code.txt
Stop input when the sentinel, '*', is found.
cipher2.cpp uses a cin.get() so that spaces
won't be skipped.
Exercise
p.
122, #2
Read sec. 7.3 for Friday.