FILE IO TEST DRIVEN DEVELOPMENT MAKEFILES IT...TEST DRIVEN DEVELOPMENT MAKEFILES Problem Solving...

Preview:

Citation preview

FILE IO TEST DRIVEN DEVELOPMENT MAKEFILESProblem Solving with Computers-I

IT

I/O in programsDifferent ways of reading data into programs • Standard input (stdin) using cin • Command line arguments (int main(int argc, char* argv[]) • Read from file

Ways to output data • Standard output: cout • Standard error: cerr • Write to file

Different ways of inputloatprutin Ct'tprograms

stdjq.geafpgdf.siainkin

ein ai terminalwrite.IE yprog 42

yggprogra

file txt

prog RAM file txt

F

itCoutcc Hello

Wor

writing

D XTprog animalstxt

includeCfstreamint main C

of stream outanimals txtoft openC 1

out a Duck Inout a Hen Inout close C

return 03

Writing to files#include <fstream> ofstream ofs; // Create a ifstream object ofs.open(“animals.txt”); //Open a file to write to ofs<<“Duck\n”<<“Cat\n”<<“Cow\n”;

Reading from files• Open a file • If open fails, exit • In a loop

• Read a line • If you reach the end of file, break • Else process the line that was read

• Close the file

Reading from a file

inDucu

TDeiEEdii.tprograminclude Lfstream

Using namespacestd

int main Cstring lineif stream in

in open Yanimals txt

if tin 3Cerra Openfailedreturn o line read

Jetline in l.infofkcoutCctne.scendlgetlineCin einecontcclinekcendlgettin Cin lines XRead line

beyond the

return 0 end of filekin is false

Assume in is a ifstream variable that was

used to open a file Assam open was successful

write code that reads all the linesin thefree

iteratively using loopsand prints each line

to std out All the different waysare correct

Awhile in

getline inline

if loin 11checkforendoffile

break

Coates line Kend

B while in

getline fin line

if in 3

yoursline aend

getline C in line

white in

out a link

getlinein line

11Accumulator pattern

string resultresult

getline C in line duckcat cow

while in

result result line

get line in line

a

Coutu result

Reading from files#include <fstream> ifstream ifs; // Create a ifstream object ifs.open(“numbers.txt”); //Open a file to read if(!ifs){ // open failed } getline(ifs, line); // read a line from the file into a // string line.

// If you attempt to read past the end // of file, ifs change to false

// If the file was empty, ifs will be false at this point ifs.close()

FILE IO: Which of the following is correct?

while(1){ getline(ifs, line); if (!ifs) break; cout<<line<<endl;}

A.

B.

C.

D.

Both A and B are correct

while(ifs){ getline(ifs, line); cout<<line<<endl;}

Neither is correct

gifs iz a if stream

variable

Recommended