Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.

Similar presentations


Presentation on theme: "© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors."— Presentation transcript:

1 © Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors

2 © Janice Regan, CMPT 128 2007-2013 1 Streams  Streams  Special objects  Deliver program input and output to/from your program  Think of a stream of output, cout  Think of a stream of input, cin  Think of << as an operator to move data from your program to an ouput stream  Think of >> as an operator to move data from an input stream into your program

3 © Janice Regan, CMPT 128 2007-2013 2 Streams  A stream can be thought of as a flow of characters  An input stream flows into your program Can come from keyboard (cin) Can come from file  An output stream flows out of your program Can go to screen (cout, or cerr) Can go to file

4 © Janice Regan, CMPT 128 2007-2013 3 Reading/Writing data (1)  Use iostream objects cin and cout  cin >> num;  Waits on-screen for keyboard entry  Value entered at keyboard is placed in the memory location reserved for variable num, that is the entered value is "assigned" to num

5 © Janice Regan, CMPT 128 2007-2013 4 Reading/Writing data (2)  cout << num;  Value from the memory location reserved for variable num, is displayed on the screen  To remember direction of >> think of it as an arrow pointing to where the data is going cin >> num; //value is being put into variable num cout << num; //value in num is being sent to the screen

6 © Janice Regan, CMPT 128 2007-2013 5 Error Output  Output with cerr  cerr works in the same way as cout  Two different streams of information cout and cerr  Both streams are displayed on the console (screen)  Can separate the two streams Display error information to the screen Redirect output to a file  Provides mechanism for distinguishing between regular output and error output.

7 © Janice Regan, CMPT 128 2007-2013 6 Other Streams  The programmer can define other streams  Stream can flow into a file  Can have multiple streams each flowing into their own file  Streams can flow out of files  Can have multiple streams each flowing out of its own file  Programmer defined streams can be used like C++ defined streams cin, cout, and cerr  Each stream actually has more flexibility and functionality than we have discussed so far

8 © Janice Regan, CMPT 128 2007-2013 7 File I/O Libraries  To access the objects and functions needed to use your own streams  You need the library fstream #include using namespace std;

9 © Janice Regan, CMPT 128 2007-2013 8 Create a stream  First create a stream to read from  Declare a variable of type ifstream ifstream myInputStream;  OR a stream to write to  Declare a variable of type ofstream ofstream myOutputStream;  Types ifstream and ofstream are defined in library fstream

10 © Janice Regan, CMPT 128 2007-2013 9 Connect your file to the stream  Once you have declared a variable to refer to the input or output stream then you need to connect your input or output file to that stream.  This process of connecting to the file is called “opening the file” myInputStream.open("infile.txt“); myOutputStream.open(“outfile.txt”);

11 © Janice Regan, CMPT 128 2007-2013 10 File Names  The filenames "infile.txt“, “outfile.txt” used in the open statement refer to files that exist (for read or write) or will be created (for write) on your computers disk.  If input or output files are kept in the same folder as the executable then infile.txt and outfile.txt will be the actual names of the files  Otherwise infile.txt and outfile.txt must be paths to the files for example D:\CourseData\cmpt128\try123\infile.txt

12 © Janice Regan, CMPT 128 2007-2013 11 Using files for input / output  Within C++ programs information is read from files or written to files  The file name (path) of the file saved on the computer’s disk for example infile.txt or outfile.txt is used only to connect to the stream you create in your program  All access to the file once it has been opened is done using the stream name for example myInputStream or myOutputStream

13 © Janice Regan, CMPT 128 2007-2013 12 Reading data from a file  cin is an input stream  You have now declared and connected to your own input stream myInputStream  To read data from your input stream use myInputStream just like you used cin to read from the keyboard stream myInputStream >> variablename;

14 © Janice Regan, CMPT 128 2007-2013 13 Writing data to a file  cout is an output stream  You have now declared and connected to your own output stream  To write data to this stream use myOutputStream just like you used cout myOutputStream << variablename;

15 © Janice Regan, CMPT 128 2007-2013 14 Breaking the connection  When the program has completed reading from or writing to the file, the connection to the file is no longer needed.  The programmer needs to break the connection between the program and the file myInputStream.close(); myOutputStream.close();

16 © Janice Regan, CMPT 128 2007-2013 15 Checking if the file opened  Sometimes we are unable to open a file  File does not exist, cannot be found  We cannot create the new file Disk is full Can not write where we asked to create the file  Need to check that the file was actually opened if ( myOutputStream.fail( ) )

17 © Janice Regan, CMPT 128 2007-2013 16 Check: using function fail( )  Need to check that the file was actually opened myOutputStream.open(“infile.txt"); if ( myOutputStream.fail( ) ) { cout << "File open failed.\n"; exit(1); }

18 © Janice Regan, CMPT 128 2007-2013 17 File Example: Simple File Input/Output (1) #include using namespace std; int main () { ifstream inStream; ofstream outStream; //declare variables and constants double meanValue = 0.0; double input1=0.0, input2 = 0.0; double input3 = 0.0, input4=0.0; inStream.open("inputFile"); if ( inStream.fail( ) ) { cerr << "inputFile not opened" << endl; return 1; } outStream.open("outputFile"); if ( outStream.fail( ) ) { cerr << "outputFile not opened" << endl; return 2; }

19 © Janice Regan, CMPT 128 2007-2013 18 File Example: Simple File Input/Output (2) myInStream >> input1 >> input2 >> input3 >> input4; meanValue = (input1+input2+input3+input4)/4.0; myOutStream << "The mean of the first four input values is "; myOutStream << meanValue << endl; myInStream.close( ); myOutStream.close( ); Input FileOutput File 1.5 4.5 5.2 2.8 4 The mean of the first four input values is 3.50

20 © Janice Regan, CMPT 128 2007-2013 19 Formatting Output  We have seen how to format output on stream cout using manipulators  We can use the same manipulators to format on any output stream

21 © Janice Regan, CMPT 128 2007-2013 20 Opening output files  When you open an output file using the C++ syntax we have discussed  You are able write information to the file  The information you write after you open the file will begin at the beginning of the file  If the output file does not exist it will be created  If the output file already exists when you open it, then the information you write will overwrite any information already in the file  What if you want to add information to the end of an existing file instead? The process of adding information to the end of the file is called appending information to the file

22 © Janice Regan, CMPT 128 2007-2013 21 Appending to a File ofstream outStream; outStream.open("important.txt", ios::app);  If file doesn’t exist it will be created  If file already exists information will be added to the end of the existing file

23 © Janice Regan, CMPT 128 2007-2013 22 Rereading from a file  If you want to reread the data in a file you can  Close the file, Clear any status saved from the last use of the file. Reopen the file. inStream.open("stuff.txt"); ⋮ inStream.close(); inStream.clear(); inStream.open("stuff.txt"); ⋮ inStream.close();

24 © Janice Regan, CMPT 128 2007-2013 23 Checking End of File  In many situations we have an input file containing data with the following properties  Data for many sets of observations (e.g. name and age and student number for a series of students)  Data contains an unknown number of sets of observations  In these situations we often want to read and process each set of observations sequentially:  Read and process each set of observations  Begin with the first set in the file  Continue until the last set is processed  Done when the end of the file is reached  To implement solutions of this type we need to be able to test to see if we are at the end of the file

25 © Janice Regan, CMPT 128 2007-2013 24 Endfile controlled Loop // Data is read from a file, one line (three values at a time // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen ifstream infile; double v1,v2, v3, cost; infile.open(“filename”); // should check if file has been opened infile >> v1 >> v2 >> v3; while ( !infile.eof( ) ) // while not at the end of file { cost += (v1 + v2 / v3); infile >> v1 >> v2 >> v3; } infile.close( ); cout << “Total cost is “ << cost << endl;

26 © Janice Regan, CMPT 128 2007-2013 25 Endfile controlled Loop T infile.eof( ) infile >> v1; Initial statement Loop condition F Statement 1; … Statement m; Update statement

27 © Janice Regan, CMPT 128 2007-2013 26 // Data is read from a file, with one value on each line // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen #include …. ifstream infile; infile.open("filename"); // should check if file has been opened while ( !infile.eof() ) { if( !( infile >> v1) && !infile.eof() ) { exit(1)} // exit if variable is not read cost += v1; } infile.close( ); cout << "Total cost is " << cost << endl; Check if variable was read

28 © Janice Regan, CMPT 128 2007-2013 27 Buffered output (1)  When writing output to a file  Output is temporarily stored in an internal buffer  Output from multiple write statements may be stored in the same buffer  Output is only written to the screen when the buffer is full. Output is written one buffer at a time.  Closing the file causes the last partially full buffer to be written to the screen  What happens to the output buffer when the program stops due to an error?

29 © Janice Regan, CMPT 128 2007-2013 28 Buffered output (2)  When a program stops for an error, the final partially full buffer may not be printed  When a program requires that output be displayed immediately (not buffered) outStream.flush();  Member function flush, for all output streams  All buffered output is written immediately

30 © Janice Regan, CMPT 128 2007-2013 29 Return Value controlled Loop T infile >> v1 Loop condition F Statement 1; … Statement m;

31 Catching a character int main() { int numOne; cout "; while ( !(cin >> numOne) ) { cin.clear(); //clears the error flag cin.sync(); //removes remaining characters from the input stream //NEVER NEVER use cin.sync() if there is no data in the input stream cout << "You typed a character not an integer, Try again" << endl; } cout << "The integer you entered was: " << numOne <<endl; return 0; } © Janice Regan, CMPT 128 2007-2013 30


Download ppt "© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors."

Similar presentations


Ads by Google