| | |
C++ Extracting data from text files
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Aug 2008
Posts: 11
Reputation:
Solved Threads: 0
C++ reading text files
I have a program which I am writing which manages a savings club. I have set up a functions which creates members (there are two members types) and outputs there data to a text file a line at a time in the format string, int, int, date(name, account number, balance, date). I have also written a host of other functions which modify the balances and so on.
My question is, how would I go about loading this data in from a file for use in the program so that the data can be used in my functions. I would also like to know how you would search the text file with say using the account holders name and bring up all the assoiated associted account data (one line of this text file is one account). The below code is what creates the data within the file (albiet this has been shortend and altered so that it can work alone). I would like to extract that data so that I can calculate an individual members interest etc.
One other problem, the code below is a shorted version of the code for use in my main program. It outputs data to the file, but for some reason everytime I run it, it deletes whats in the file junmembers.txt and replaces it with the new data, even though I have loaded the file in append mode. Here is my code
I have a program which I am writing which manages a savings club. I have set up a functions which creates members (there are two members types) and outputs there data to a text file a line at a time in the format string, int, int, date(name, account number, balance, date). I have also written a host of other functions which modify the balances and so on.
My question is, how would I go about loading this data in from a file for use in the program so that the data can be used in my functions. I would also like to know how you would search the text file with say using the account holders name and bring up all the assoiated associted account data (one line of this text file is one account). The below code is what creates the data within the file (albiet this has been shortend and altered so that it can work alone). I would like to extract that data so that I can calculate an individual members interest etc.
One other problem, the code below is a shorted version of the code for use in my main program. It outputs data to the file, but for some reason everytime I run it, it deletes whats in the file junmembers.txt and replaces it with the new data, even though I have loaded the file in append mode. Here is my code
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <fstream> #include <date> using namespace std; int main() { string a; string n; int b; int aNum; int date; ofstream jun("file.txt", ios::app | ios::ate ); if (jun.fail ()) { cout << "Error opening file, program closing" << endl; exit(1); } cout << "Please enter a name" << endl; cin >> n; cout << "Please enter an age" << endl; cin >> a; cout << "Please enter an expiry date" << endl; cin >> date; srand ( time(NULL) ); // this seeds the random number so it will not be dulplicated aNum = rand() % 999 + 1000;/* The random number generator here is producing a random number between 0 and 999 and then will make the random value be within the range of +1000 - +1999 as it is addingg 1000. Accounts with numbers begining with 1 will be Junior accounts and accounts with numbers beggining with 2 will be Full accounts */ b = 0; //default balance will be nil or 0 jun << n << " " << aNum << " " << b << " " << a << " " << date << endl;//output to file jun.close(); }
Last edited by davidleeis14; Aug 4th, 2008 at 11:11 am.
For reading data from text files: ifstream
I'm a student. If my statements seem too absolute, feel free to coat them with "In my opinion..." or "I believe...".
The last problem:
Don't use
). If you want to append new records use ios::app only. If you want to append a record then seek and write at any other place (it's not your case with a text file), use:
The main problem is more complicated:
1. You can't update lines in an existing text file: you must create a new file, write an updated contents then discard an old file then rename a new one - or rewrite an old file from the scratch. A file is only byte sequence, a line of a text file is a byte sequence terminated with '\n' or '\r' '\n' (depends of a target system). You can't ask a system to update i-th line - a system does not understand you (what is it: i-th line? Only you know!)
2. Try to load your "text database" file at the start of your program. Invent a proper structure - for example, use std::vector<MemberRecord>. Make add/update/erase operations under this structure. Write this structure back to the "text database" at the end of your program run. In addition you will get much more simpler and suitable for search/add/erase ops structure than cumbersome and unrobust mechanics with data file direct access.
Don't use
ios::app|ios::ate flags together: ios::ate suppresses ios::app and truncate the file (don't ask me why now
). If you want to append new records use ios::app only. If you want to append a record then seek and write at any other place (it's not your case with a text file), use: cpp Syntax (Toggle Plain Text)
fstream f(filename,ios::in|ios::out|ios::ate);
The main problem is more complicated:
1. You can't update lines in an existing text file: you must create a new file, write an updated contents then discard an old file then rename a new one - or rewrite an old file from the scratch. A file is only byte sequence, a line of a text file is a byte sequence terminated with '\n' or '\r' '\n' (depends of a target system). You can't ask a system to update i-th line - a system does not understand you (what is it: i-th line? Only you know!)
2. Try to load your "text database" file at the start of your program. Invent a proper structure - for example, use std::vector<MemberRecord>. Make add/update/erase operations under this structure. Write this structure back to the "text database" at the end of your program run. In addition you will get much more simpler and suitable for search/add/erase ops structure than cumbersome and unrobust mechanics with data file direct access.
I'm a student. If my statements seem too absolute, feel free to coat them with "In my opinion..." or "I believe...".
firstly, you need to have a structure that can hold all the data that you need. In the example, this would be vector<MemberRecord>. As far as loading a MemberRecord into your program, you have a couple of options. Say you store data like this:
Meaning that John is 42 and has $15.69 and Bill is 34 years old and has $17.89. Say your structure looks like this:
You could extract the data manually:
Or you could define a custom extraction operator for it:
C++ Syntax (Toggle Plain Text)
John 42 15.69 Bill 34 17.89
Meaning that John is 42 and has $15.69 and Bill is 34 years old and has $17.89. Say your structure looks like this:
C++ Syntax (Toggle Plain Text)
struct MemberRecord { std::string name; int age; float balance; };
You could extract the data manually:
C++ Syntax (Toggle Plain Text)
MemberRecord mem; ifstream fin("myfile.txt"); fin >> mem.name >> mem.age >> mem.balance; myvector.push_back(mem);
Or you could define a custom extraction operator for it:
C++ Syntax (Toggle Plain Text)
ifstream& operator>>(ifstream& fin,MemberRecord& mem) { fin >> mem.name >> mem.age >> mem.balance; } //... in some other function: fin >> mem; myvector.push_back(mem);
I'm a student. If my statements seem too absolute, feel free to coat them with "In my opinion..." or "I believe...".
Oh - sorry, there was an error in my overloaded extraction operator:
ifstream& operator>>(ifstream& fin,MemberRecord& mem)
{
fin >> mem.name >> mem.age >> mem.balance;
return fin;
} I'm a student. If my statements seem too absolute, feel free to coat them with "In my opinion..." or "I believe...".
Well, CoolGamer48 got rights answers to all your questions...
May be it helps too (regrettably, I can't invent a very brief and clear example
):
May be it helps too (regrettably, I can't invent a very brief and clear example
): cpp Syntax (Toggle Plain Text)
class Record { public: Record(): age(0) {} explicit Record(const char* pline); explicit Record(const string& line); Record(const char* pname, int age); Record(const string& newname, int newage); const string& getName() const { return name; } const string& setName(const char* pname) { if (pname) name = pname; return name; } const string& setName(const string& newname) { return name = newname; } int getAge() const { return age; } int setAge(int newage) { if (newage >= 0 && newage < 150) age = newage; return age; } bool parse(const string& line); string toString() const; private: static char delim; string name; int age; }; ostream& operator << (ostream& os, const Record& r) { os << r.getName() << " " << r.getAge(); return os; } char Record::delim = '|'; Record::Record(const char* pline):age(0) { parse(pline); } Record::Record(const string& line):age(0) { parse(line); } Record::Record(const char* newname, int newage):age(0) { setName(newname); setAge(newage); } Record::Record(const string& newname, int newage):age(0) { setName(newname); setAge(newage); } bool Record::parse(const string& line) { istringstream ins(line); char namebuf[64]; if (!ins.get(namebuf,sizeof namebuf,delim)) return false; ins.ignore(1); int age; if (ins >> age) { name = namebuf; setAge(age); return true; } else return false; } string Record::toString() const { ostringstream ost; ost << name << delim << age; return ost.str(); } class PlainDb { public: int load(const char* fname); int load(const string& fname) { return load(fname.c_str()); } int save(const char* fname); int save(const string& fname) { return save(fname.c_str()); } Record& operator [](int i) { return i >= 0 && i < size()? db[i]: dummy; } int findByName(const char* pname) { if (pname) { string sname(pname); for (int i = 0; i < size(); ++i) if (db[i].getName() == sname) return i; } return -1; } int findByName(const string& sname) { return findByName(sname.c_str()); } int size() const { return db.size(); } private: static Record dummy; vector<Record> db; }; Record PlainDb::dummy("Unknown",0); int PlainDb::load(const char* fname) { int nrecs = -1; if (fname) { ifstream f(fname); if (f) { Record r; string line; for (nrecs = 0; getline(f,line); ++nrecs) { if (!r.parse(line)) return -1; db.push_back(r); } } } return nrecs; } int PlainDb::save(const char* fname) { int nrecs = -1; if (fname) { ofstream f(fname,ios::ate|ios::trunc); for (nrecs = 0; nrecs < size(); ++nrecs) { f << db[nrecs].toString() << "\n"; if (f.bad()) return nrecs?-nrecs:-1; } f.flush(); } return nrecs; } void dbTest(const string& dbname) { PlainDb db; if (db.load(dbname) <= 0) return; int i = db.findByName("Jesus"); if (i >= 0) { db[i].setName("Maria"); db[i].setAge(18); db.save(dbname); } }
![]() |
Similar Threads
- adware.purityscan (Viruses, Spyware and other Nasties)
- Storing Text file in Database through VB (Visual Basic 4 / 5 / 6)
- spyware, pop-ups and more; amaena?? (Viruses, Spyware and other Nasties)
- adware.purityscan (Viruses, Spyware and other Nasties)
- very weird drive problems (Storage)
- urgent (C)
- Beginner needs assistance with 'error checking' program (C++)
Other Threads in the C++ Forum
- Previous Thread: plotting cpu and mem consumption
- Next Thread: HELP ME MY MISTAKE and HELP THE CORRECT The my homework
| Thread Tools | Search this Thread |
api array beginner binary bitmap c++ c/c++ calculator char char* class classes coding compile compiler console conversion count data database delete desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game getline google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates test text text-file tree unix url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






