In many instances of reading data from a file we must skip several lines
of text and zoom into the lines which contain the numerical data we need.
An easy device for achieving this is the I/O stream member function
.getline which is used in conjunction with a file stream. The arguments
of the function .getline are a) a character array and b) the size of the
array.
The following example illustrates the use of this function.
|
|
/* An example on the use of .getline() : file: 6ex6.cpp FALL 1998 ___________________________________ Jacob Y. Kazakia jyk0 October 21, 1998 Recitation Instructor: J.Y.Kazakia Recitation Section 01 ___________________________________ Purpose: This program reads from a file named 6ex6data.txt.
It uses the function .getline to skip the first
few lines of the file and then reads the second
line of the numerical data. The file 6ex6data.txt looks like this:
|
We must skip three blank lines, four lines of characters and one line
of numerical data before we can get to the nonzero numbers that we need
to read . In other words, we must skip 8 lines. |
___________________________________________________________ THE DRAG FORCE CALCULATED FOR AN OBJECT OF FRONTAL AREA 2 m2 USING cd = 0.3 Speed Drag Force m/s miles/hour Newtons Pounds 0 0 0 0 5 11.1857 9.1875 2.06553 10 22.3714 36.75 8.26214 15 33.557 82.6875 18.5898 20 44.7427 147 33.0485 25 55.9284 229.688 51.6383 30 67.1141 330.75 74.3592 35 78.2998 450.188 101.211 40 89.4855 588 132.194 End of this table ___________________________________________________________
*/
|
The variables are declared and the character array a is declared.
The length of the array is 80 ( we can store the first 80 characters per
line) . The stream table is identified. |
#include <iostream.h> #include <iomanip.h> #include <fstream.h> void main() { // declare the variables of the main function float speedMPS; float speedMPH; float dragNEWTONS; float dragPOUNDS; char a[80]; // array used to store the data read from the first 8 // lines int m; ifstream table ( "6ex6data.txt" , ios:: in);
|
This is the point where we use .getline to skip 8 lines of data we don't
need. Each time we read a line the information in the array a is overwritten. |
for ( m = 0 ; m <= 7 ; m++ ) { table.getline( a, 80 ); }
|
|
// read the data desired table >> speedMPS >> speedMPH >> dragNEWTONS >> dragPOUNDS; // output the data cout << " \n speed in meters per second " << speedMPS ; cout << " \n speed in miles per hour " << speedMPH ; cout << " \n drag force in Newtons " << dragNEWTONS ; cout << " \n drag force in pounds " << dragPOUNDS ; cout<<" \n\n enter e (exit) to terminate the program...."; char hold; cin>>hold; }
|
© 2001 J.Y. Kazakia. All rights reserved