Reading from file (into char arrays)

Hey all,
I've been trying to figure out my problem for the past few days and haven't gotten any closer :(

I have "names.txt" which i am trying to read from consisting of:
Johnjames
150
Bob Uncle
630
Jimmy mayo
394
...... (list of about 10 entries like this)

And im trying to store them into this structure.

Here is the code i'm using, (this able to get the first name and number perfectly fine, but spits out garbage afer.)
I've opened the file etc, everything works fine, i just need to store the data!
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
34
#include <iostream>
#include <fstream>

using namespace std;

struct client
{
	char name[50];
	int number;
};

int main()
{
		
	fstream namefile;
	namefile.open("names.txt", ios::in);
	if(!namefile.good())
		cout << "FILE OPENING ERROR!!" << endl;

	client identity[10];

	namefile.getline(identity[0].name, 50, '\n');
	namefile >> identity[0].number;
	namefile.getline(identity[1].name, 50,'\n');
	namefile >> identity[1].number;
	
	cout << identity[0].name << endl;
	cout << identity[0].number << endl;
	cout << identity[1].name << endl;
	cout << identity[1].number << endl;

return 0;
}
	


This is a simplified version of my code, but still has the same problem.

please help :(
Thanks all!!
1
2
3
4
5
6
7
8
9
10
11
12
enum { N = 10, NAMESZ = sizeof(client::name) } ;

client ident[N] = { { "", 0 } } ;
std::ifstream file( "names.txt" ) ;

for( int i=0 ; i<N ; ++i  )
{
   if( file.getline( ident[i].name, NAMESZ, '\n') && file >> ident[i].number )
        file.ignore( 1024, '\n' ) ; 

   else break ;
}


see: http://cplusplus.com/forum/general/69685/#msg372532
Thanks a lot JLBorges!!

Worked a charm!!
Topic archived. No new replies allowed.