Lab 4 fstream, compare, eof().



CSC230 Lab 4

Goal: This lab includes function and arguments passing. You will use fstream,
compare, eof().
Please try your best to finish the lab in class, and submit it to CANVAS.
In this lab, please write a Lab4.cpp file. There is main function in this file. Please do not
define additional functions in this lab.
The program Lab4.cpp reads contents from input file, which is “sample.txt” in today’s
lab. Each row of the input file has a leading char, followed by a string of SSN, and first
name and last name. The program stores SSN and the corresponding name (including
both first name and last name) to an array. After the whole input file is processed, the
program prompts the user to type a SSN, then it will search the SSN in the array. If there
is a match, the program prints out the index value of the entry. For example,
jli$ ./a.out sample.txt
Input a SSN:
Found at location 4
jli$ ./a.out sample.txt
Input a SSN:
Found at location 8
In this lab, you can use fstream library to read file. An example code is listed as follows:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
int x, y, z;
fstream input(argv[1]);
input >> x >> y >> z;
if(!input) break;
In the above example,
• the file name is stored in argv[1]
• eof() checks whether we are reaching the end of file. If yes, it returns true;
otherwise, false. eof() is similar to hasnext() method in Java.
• each row of the input file has three integers, the while loop reads these three
integers and stores them in variables x, y, and z
• it is a good idea to close the file if you do not need it any more
There are several requirements in this lab:
• Define a struct, which has two string variables – SSN and name.
• Use the struct to statically define an array with size 1000.
• If you have string variables, s1, s2, and s3. You can have statements:
o s1 = s2;
o s1 = s2+s3;
o if( == 0) // checks equality of s1 and s2
• The array size is 1000, but the number of entry can be smaller than 1000. You
need a counter variable to record the size of the entry.
Wrap up
When you’re done, jar three files to lab4.jar
jar –cvf lab4.jar *
Submit lab4.jar to Canvas.
Make sure you logout before you leave!
If you cannot finish lab in class, please save all your files. Next time you login the
computer in the lab, you can continue work on your files. Please save them before you
logout. If you work in a Linux lab, please save the file to your machine. However, if you
are working in the Mac lab, please save the file to a CLOUD. The Mac machine will
erase everything you saved once you logout.


There are no reviews yet.

Be the first to review “Lab 4 fstream, compare, eof().”

Your email address will not be published.