I am working on reading data from a file into a struct array. The first line of the file tells how many users there are, then the following lines are the username, password, and a pincode.So the file is setup as follows:


My array needs to be able to handle a maximum of 50 users. I successfully read in the number of users and the first username, password, and pincode but then it stops reading.

Here's my code

#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>

using namespace std;

int main()
	const int MAX_USERS = 50;	//constants
	int count;
	ifstream inFile;

	 while(!inFile) //loop to notify user of invalid file
        cout << "Error: File not found. " << endl;  // invalid entry occurred
                                                         // message is printed
       return 0;

	struct UserLogin					//struct to store data
		string userName;
		string passWord;
		int userPin;
		int currentUsers;

	UserLogin loginInfo[MAX_USERS];

	for (count = 0; count < MAX_USERS; count++) // loop to read data from file
		inFile >> loginInfo[0].currentUsers;
		inFile >> loginInfo[count].userName;
		inFile >> loginInfo[count].passWord;
		inFile >> loginInfo[count].userPin;

	cout << loginInfo[0].currentUsers << setw(5) << loginInfo[1].userName << setw(10) << loginInfo[1].passWord << setw(6) << loginInfo[1].userPin << endl;

	return 0;

The last line is being used to test to print out the data when i get the data to read in correctly.

For starters, you need to move your struct definition out of your main(). Put it after your using statement. Your recordCount should be separate from your struct, it should not be part it.

After you verify that you have successfully opened your file, you should do an initial read to get your recordCount. Then, use your for loop to read the rest of the file. The condition that controls your for loop would be based on the value of recordCount, so long as it's less than your array size (your maxUsers value). If you base it on maxUsers, you run the risk of overruning the end of your file and making a mess of your input stream.

Each of your users only has 3 pieces of data, yet you do 4 reads per iteration. Can you see how your file read will get out-of-synch with your data after only one (1) iteration? You need to remove Line 39. From what I can tell, this is intended to fill the role of your initial file read that I mentioned earlier. This is not the proper way to do it.

Thank you so much. It makes sense now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.