File IO

Hey guys
I have this file that i need to display.

10
1 1000.25
2 55.25
3 9999.99
4 33.45
5 2000.00
6 1588.88
7 1699.99
8 14898.25
9 13734.21
10 13523.24

I need to skip the first line and then display the rest.
My code mess up the first line and the second one
Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>

using namespace std;

int main(){

	string filename = ("prices.dat");
	int id, count;
	double price;

	ifstream inFile;
	inFile.open(filename.c_str());

	if(inFile.fail()){
		cout <<"\nThe file was not succesfully open"
			<<"\nPlease check that the file exits"
			<< endl;
		exit(1);	
	}

	while(!inFile.eof()){
		inFile >> id >> price;
		count++;
		cout << id << "	" << fixed <<setprecision(2) << price <<  endl;
	}
	
	inFile.close();

	return 0;
}

Is anyone keen to help me ?
Thanks guys
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
if (myfile.is_open())
  {
    myfile >> first stuff
    while ( myfile >> later stuff >> ...  )
    {
      // do stuff cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file";
closed account (48T7M4Gy)
PS you might want to include trapping if the pattern of the file structure doesn't fit the read pattern eg the first line is missed out.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;

int main()
{
   string filename = "prices.dat";                         // <==== no brackets needed
   int id;
   int numItems;
   double price;
   int count = 0;                                          // <==== ***** initialise count *****

   ifstream inFile( filename );                            // <==== simplify (use .c_str() if compiler is c++98 only)
   if ( !inFile ) { cout << "File-open failure\n";   exit(1); }

   inFile >> numItems;                                     // <==== presumably the intention
   cout.precision( 2 );   cout.setf( ios::fixed );         // <==== applies to floating-point only, and "sticky"
   while( inFile >> id >> price )                          // <==== use stream status to control looping (or could use numItems and a for loop)
   {
      count++;
      cout << setw( 3 ) << id << " " << setw( 10 ) << price << '\n';    // <==== formatting
   }

   cout << "Number of items declared: " << numItems << '\n'; 
   cout << "Number of items read: "     << count    << '\n';
   
   inFile.close();
}


  1    1000.25
  2      55.25
  3    9999.99
  4      33.45
  5    2000.00
  6    1588.88
  7    1699.99
  8   14898.25
  9   13734.21
 10   13523.24
Number of items declared: 10
Number of items read: 10

Last edited on
Topic archived. No new replies allowed.