Transcript Text Files

TEXT FILES
CIN / COUT REVIEW
 We are able to read data from the same line or multiple lines during
successive calls.
 Remember that the extraction operator (>>) skips any leading white
space (spaces, tabs, newlines) characters before reading the data.
User Input
45 67\n
3 8\n
int num1, num2,
num3, num4;
cin >> num1;
cin >> num2;
cin >> num3;
cin >> num4;
num1 = 45
num2 = 67
num3 = 3
num4 = 8
CIN / COUT REVIEW
 If you want to skip past ALL remaining data (not just white space) on
a line and go to the next line, you can use cin.ignore().
User Input
45 67\n
int num1, num2;
3 8\n
cin >> num1;
cin.ignore(100, ‘\n’);
cin >> num2;
num1 = 45
skips remaining data on line 1
num2 = 2
CIN / COUT REVIEW
 If you want to read all characters (includig whitespace characters
instead of skipping past them) you can use the cin.get() to read into
char type variables.
char ch1, ch2, ch3, ch4, ch5;
User Input
4\n
3 8\n
cin.get(ch1);
cin.get(ch2);
cin.get(ch3);
cin.get(ch4);
cin.get(ch5);
ch1 = ‘4’
ch2 = ‘\n’
ch3 = ‘3’
ch4 = ‘ ‘
ch5 = ‘8’
CIN / COUT REVIW
 To display output to the screen we used “cout”.
 The cursor remains where the last output occurs unless “endl” or
“\n” is added ( this allows more output to be added to same line).
CODE
OUTPUT
cout << “Hello”;
cout << “Hello” << endl;
Hello_
Hello
_
cout << “Good”;
cout << “bye”
Goodbye_
CIN / COUT REVIEW
 Output can be formatted using manipulators:
fixed
setw()
setprecision()
forces floating point number to be displayed in a
decimal format (instead of scientific)
sets the display with of output data
sets number of decimal places to be displayed
int num = 456;
float val = 4.8728;
cout << fixed << showpoint << setprecision(2);
cout << val;
cout << setprecision(1) << val;
cout << setw(4) << val;
cout << setw(1) << num;
cout << setw(5) << num;
OUTPUT
4.87
4.9
_4.9
456
__456
CIN / COUT REVIEW
 “cin” will read data according to the data type of input variable
 Reading strings stops at the first whitespace character
 Using “getline()” forces all characters on line to be read
Input data:
435 8.8“\n”
int num; float value; char ch; string words
cin >> value >> ch;
value = 435.0, ch = ‘8’
cin >> ch >> num;
ch = ‘4’, num = 35
cin >> words >> num >> value;
words = “435”, num = 8, value = 0.8
getline(cin, words);
words = “435 8.8”
cin >> ch >> ch >> value >> words;
ch = ‘3”, value = 5.0, words = “8.8”
TEXT FILES
Text File
File Of ASCII Characters
 Can Be Viewed In Text Editor
Last Character On Line Is “newline” Character (‘/n’)
Last Character In The File Is “eof” Character
Can Be Created With Any Text Editor (notepad, compiler…)
Input File Stream
Stream Of Data
Same As Keyboard Input But From The File
Input File Stream Can Be Tricky
TEXT FILES
File Examples
character (or string) Data:
This Is A Test. This Is Only A Test.(‘/n’)
Now Is The Time For All Good Men(‘/n)
To Come To The Aid Of Their Country.(‘/n’)
(eof)
Mixed Data:
Smith Joe 111-11-1111 3.85(‘/n)
Able Sam 222-22-2222 3.25(‘/n)
Blow Joe 333-33-3333 2.50(eof)
USING TEXT FILES
Five Steps For File Access
# 1 – Add “#include <fstream>” To Top Of Program
Adds Library For File Access
# 2 – Declare File Stream Variable
Use Valid Identifier Name
Separate File Stream Variables are Required For Text Files
Which are Dependant On the Mode (“read” or “write”)
– For Input Stream
• ifstream Identifier - example:
ifstream inData;
– For Output Stream
• ofstream Identifier - example:
ofstream outData;
USING TEXT FILES
Five Steps For File Access (cont.)
#3 – Open The File Stream
Use The “open” Function
file-stream-variable.open(physical file name)
example:
inData.open(“c:\test.txt);
example:
const string FILENAME = “test.txt”;
outData.open(FILENAME.c_str());
Note:
You may need to list all backslashes as double backslashes in file
names
(e.g. “c:\\study.txt”).
Note:
file-stream-variable must be of type ifstream or ofstream
physical filenames can be a literal string or a C string variable
(must append “.c_str()” onto the variable name to convert it to a C string – and
be sure to include the “string” header file).
USING TEXT FILES
Five Steps For File Access (cont.)
Potential File “Path” Issues
Opening Input File Stream (read only)
Checks For File Existence
If Exists
If Missing
File Opened, Read Pointer Placed At Beginning and
File Stream In Non-Error State
File Stream Is Put Into Error State
Opening Output File Stream (write only)
Checks For File Existence
If Exists
If Missing
File Opened, All Data Erased, File Ready For Data
New File Opened, File Ready For Data
Note – Text Files Can Only Be Open In One Mode At A Time (Read or Write)
USING TEXT FILES
Five Steps For File Access (cont.)
File Stream Status Can Be Used For Error Checking
After opening file “figures.txt” for reading, use the file stream variable
to check the results.
inData.open("figures.txt");
if ( !inData )
cout << "Error opening file!" << endl;
else
{
// continue program
}
Result: Error message is issued if program was not able to open file
figures.txt.
USING TEXT FILES
Five Steps For File Access (cont.)
#4 – Read Or Write Data File
Similar To Standard Input/Output Process
Instead Of Using “cin” Use File Stream Variable
– File “study.txt” contains:
35.75 47(‘\n’)
36.50 54(‘\n’) <eof>
– Code:
double num1; int num2;
ifstream inData; ofstream outData;
inData >> num1;
inData >> num2;
\\Reads First Number
\\Reads Second Number
results:
num1 = 35.75, num2 = 47
USING TEXT FILES
Five Steps For File Access (cont.)
Instead Of Using “cout” Use File Stream Variable
Use Of “manipulators” For Formatting Data Has The Same
Affect On Output File As They Do With Displayed Output
(..setprecision(), setw()…etc)
double num1, num2;
– Code:
num1 = 53.75875;
num2 = num1 * 2; (106.3175)
outData << fixed << showpoint << setprecision(2);
outData << setw(6) << num1 << ‘ ‘ << set(6) << num2
<< endl;
– Result:
_53.76 _106.32(\n’)
<eof>
USING TEXT FILES
Five Steps For File Access (cont.)
#5 – Close The Open File When Finished
As Soon As File Access Is Completed, Files Should Be
Closed
inData.close();
outData.close();
Leaving Files Open When Not Needed Increases Opportunity
Of Corrupted Files
Using Text Files
Five Steps
Include “fstream” Header File At Top Of Program
Declare File Stream Variables (ifstream or ofstream)
Open The Data File
Use File Stream Variable To Access File (not cin/cout)
Close Any Open Files When Finished With File
Passing The File Stream To A User Defined Function
Must Always Be Passed By Reference syntax
For example:
void readFile(ifstream& inData) (function header)
void readFile(ifstream& inData); (prototype)