Reputation: 47
I'm working on a program that requires me to create a hash table from the contents of a file. The file contains records (1 per line) that include a key (int), name (string), code (int), and a cost (double). I have the code written for most of the program to create the hash table, however, I'm having some trouble figuring out how I should load the table from the file. More specifically, how to store each piece of the record into its corresponding variable?
The code is kind of long, but if you think posting it would help answer my question, let me know and I'll be glad to include it.
I do feel I should include this though, I have a struct set up to hold the information contained in each record that I have set up as follows:
struct record {
int key;
string name;
int code;
double cost;
}
If you need to see any other portions of the code, or the code as a whole, let me know.
Upvotes: 0
Views: 3488
Reputation: 1008
If the data file has white-space separated items in lines, you can use for example the following code:
#include <iostream>
#include <fstream>
using namespace std;
typedef struct record {
int key;
string name;
int code;
double cost;
} rec;
int main()
{
ifstream f ("data.txt");
rec r;
f >> r.key;
while (!f.eof())
{
f >> r.name;
f >> r.code;
f >> r.cost;
cout << "new record, key=" << r.key
<< ", name=" << r.name
<< ", code=" << r.code
<< ", cost=" << r.cost << "\n";
f >> r.key;
}
//will also be done by destructor: f.close();
return 0;
}
Upvotes: 0
Reputation: 3379
You can try this:
while(_fstream >> key && _fstream >> name && _fstream >> code && _fstream >> cost)
{
record r;
r.key = key;
r.name = name; // and so on
// now you may do whatever you want to with your r object
}
_fstream
is your opened file stream for input.
As @Red Alert mentioned, this will be a more elegant solution:
while(_fstream >> key >> name >> code >> cost)
Because _fstream >> key
returns the _fstream
itself;
Upvotes: 2