need help...read data from a file

my code is working somehow...but it stops at "Gunn", and then the .exe file has stopped working....can u guys help me to fix it?? ^.^

the data in the file
Hammet	Robert	HJ123	25.00	23.00	0.20	460.00
Gunn	Tommy	UF458	60.00	28.00	0.32	1142.40
Smither	Bobby	OF761	56.00	99.00	0.20	4435.20



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
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;

int main()
{	
	ofstream outfile;
	ifstream infile;
	string input[6];
	infile.open("personnel.txt", ios::in);
	if (infile.is_open())
	{
		getline(infile, input[0], '	');
		getline(infile, input[1], '	');
		getline(infile, input[2], '	');
		getline(infile, input[3], '	');
		getline(infile, input[4], '	');
		getline(infile, input[5], '	');
		getline(infile, input[6], '	');
				
		cout<<"\n\nLast Name: "<<input[0]<<"\nFirst Name: "<<input[1]<<"\nWorker ID: "<< input[2]<<"\nWorked Hour: "
			<<input[3]<<"\nPay Rate "<< input[4]<<"\nTax Rate: "<<input[5]<<"\nNet Pay: "<< input[6]<< endl;	
	}
	else
	{
		cout << "ERROR: Cannot open file.\n";
	}
	infile.close();
	return 0;
}


output


Last Name: Hammet
First Name: Robert
Worker ID: HJ123
Worked Hour: 25.00
Pay Rate 23.00
Tax Rate: 0.20
Net Pay: 460.00
Gunn
It stopped because you only read it once : if (infile.is_open()) { ... }
It crashed because input's size is only 6, but you read 7 data
and accessed out of bounds.

to read the file continuously , you'll need a while loop

something like :

1
2
3
4
5
6
7
8
9
10
11
string input[ 7 ];

if( infile.is_open() ) {
    while( getline(infile, input[0]) &&
           getline(infile, input[1]) &&
           // ...
         )
    {
        // print
    }
}


BTW, if you want to store and manipulate the read data later, you should consider using struct
or class and std::vector<Your_struct>..
Last edited on
thank you..it works perfectly
Topic archived. No new replies allowed.