943,844 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 6187
  • C++ RSS
You are currently viewing page 1 of this multi-page discussion thread
Aug 4th, 2008
0

C++ Extracting data from text files

Expand Post »
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

C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <fstream>
  3. #include <date>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string a;
  10. string n;
  11. int b;
  12. int aNum;
  13. int date;
  14.  
  15.  
  16. ofstream jun("file.txt", ios::app | ios::ate );
  17.  
  18.  
  19. if (jun.fail ())
  20. {
  21. cout << "Error opening file, program closing" << endl;
  22. exit(1);
  23. }
  24.  
  25. cout << "Please enter a name" << endl;
  26. cin >> n;
  27. cout << "Please enter an age" << endl;
  28. cin >> a;
  29. cout << "Please enter an expiry date" << endl;
  30. cin >> date;
  31.  
  32.  
  33. srand ( time(NULL) ); // this seeds the random number so it will not be dulplicated
  34.  
  35. aNum = rand() % 999 + 1000;/* The random number generator here is producing a
  36.  
  37. random number between 0 and 999 and then will make the
  38.  
  39. random value be within the range of +1000 - +1999 as it is
  40.  
  41. addingg 1000. Accounts with numbers begining with 1 will be
  42.  
  43. Junior accounts and accounts with numbers beggining
  44.  
  45. with 2 will be Full accounts */
  46.  
  47.  
  48.  
  49. b = 0; //default balance will be nil or 0
  50.  
  51. jun << n << " " << aNum << " " << b << " " << a << " " << date << endl;//output to file
  52.  
  53. jun.close();
  54.  
  55.  
  56.  
  57.  
  58. }
Last edited by davidleeis14; Aug 4th, 2008 at 11:11 am.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
davidleeis14 is offline Offline
11 posts
since Aug 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

For reading data from text files: ifstream
Reputation Points: 77
Solved Threads: 40
Posting Pro in Training
CoolGamer48 is offline Offline
401 posts
since Jan 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

The last problem:
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)
  1. 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.
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

Thanks for the help, but could you please expand on point number 2. ArkM. What is my text database file?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
davidleeis14 is offline Offline
11 posts
since Aug 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

Thanks for the help, but could you please expand on point number 2. ArkM. What is my text database file?
A text database file is just your text file.
Reputation Points: 77
Solved Threads: 40
Posting Pro in Training
CoolGamer48 is offline Offline
401 posts
since Jan 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

Thanks coolgamer48, but how would you load the data from the txt file into the STL Vector
Reputation Points: 10
Solved Threads: 0
Newbie Poster
davidleeis14 is offline Offline
11 posts
since Aug 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

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:
C++ Syntax (Toggle Plain Text)
  1. John 42 15.69
  2. 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)
  1. struct MemberRecord
  2. {
  3. std::string name;
  4. int age;
  5. float balance;
  6. };

You could extract the data manually:
C++ Syntax (Toggle Plain Text)
  1. MemberRecord mem;
  2. ifstream fin("myfile.txt");
  3. fin >> mem.name >> mem.age >> mem.balance;
  4. myvector.push_back(mem);

Or you could define a custom extraction operator for it:
C++ Syntax (Toggle Plain Text)
  1. ifstream& operator>>(ifstream& fin,MemberRecord& mem)
  2. {
  3. fin >> mem.name >> mem.age >> mem.balance;
  4. }
  5.  
  6. //... in some other function:
  7. fin >> mem;
  8. myvector.push_back(mem);
Reputation Points: 77
Solved Threads: 40
Posting Pro in Training
CoolGamer48 is offline Offline
401 posts
since Jan 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

Thanks a million! Will be of great help.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
davidleeis14 is offline Offline
11 posts
since Aug 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

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;
}
Reputation Points: 77
Solved Threads: 40
Posting Pro in Training
CoolGamer48 is offline Offline
401 posts
since Jan 2008
Aug 4th, 2008
0

Re: C++ Extracting data from text files

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):
cpp Syntax (Toggle Plain Text)
  1. class Record
  2. {
  3. public:
  4. Record(): age(0) {}
  5.  
  6. explicit Record(const char* pline);
  7. explicit Record(const string& line);
  8. Record(const char* pname, int age);
  9. Record(const string& newname, int newage);
  10.  
  11. const string& getName() const
  12. {
  13. return name;
  14. }
  15. const string& setName(const char* pname)
  16. {
  17. if (pname)
  18. name = pname;
  19. return name;
  20. }
  21. const string& setName(const string& newname)
  22. {
  23. return name = newname;
  24. }
  25. int getAge() const { return age; }
  26. int setAge(int newage)
  27. {
  28. if (newage >= 0 && newage < 150)
  29. age = newage;
  30. return age;
  31. }
  32. bool parse(const string& line);
  33. string toString() const;
  34. private:
  35. static char delim;
  36. string name;
  37. int age;
  38. };
  39.  
  40. ostream& operator << (ostream& os, const Record& r)
  41. {
  42. os << r.getName() << " " << r.getAge();
  43. return os;
  44. }
  45.  
  46. char Record::delim = '|';
  47.  
  48. Record::Record(const char* pline):age(0)
  49. {
  50. parse(pline);
  51. }
  52.  
  53. Record::Record(const string& line):age(0)
  54. {
  55. parse(line);
  56. }
  57.  
  58. Record::Record(const char* newname, int newage):age(0)
  59. {
  60. setName(newname);
  61. setAge(newage);
  62. }
  63. Record::Record(const string& newname, int newage):age(0)
  64. {
  65. setName(newname);
  66. setAge(newage);
  67. }
  68.  
  69. bool Record::parse(const string& line)
  70. {
  71. istringstream ins(line);
  72. char namebuf[64];
  73. if (!ins.get(namebuf,sizeof namebuf,delim))
  74. return false;
  75. ins.ignore(1);
  76. int age;
  77. if (ins >> age)
  78. {
  79. name = namebuf;
  80. setAge(age);
  81. return true;
  82. }
  83. else return false;
  84. }
  85.  
  86. string Record::toString() const
  87. {
  88. ostringstream ost;
  89. ost << name << delim << age;
  90. return ost.str();
  91. }
  92.  
  93. class PlainDb
  94. {
  95. public:
  96.  
  97. int load(const char* fname);
  98. int load(const string& fname)
  99. {
  100. return load(fname.c_str());
  101. }
  102. int save(const char* fname);
  103. int save(const string& fname)
  104. {
  105. return save(fname.c_str());
  106. }
  107. Record& operator [](int i)
  108. {
  109. return i >= 0 && i < size()? db[i]: dummy;
  110. }
  111. int findByName(const char* pname)
  112. {
  113. if (pname)
  114. {
  115. string sname(pname);
  116. for (int i = 0; i < size(); ++i)
  117. if (db[i].getName() == sname)
  118. return i;
  119. }
  120. return -1;
  121. }
  122. int findByName(const string& sname)
  123. {
  124. return findByName(sname.c_str());
  125. }
  126. int size() const { return db.size(); }
  127. private:
  128. static Record dummy;
  129. vector<Record> db;
  130. };
  131.  
  132. Record PlainDb::dummy("Unknown",0);
  133.  
  134. int PlainDb::load(const char* fname)
  135. {
  136. int nrecs = -1;
  137. if (fname)
  138. {
  139. ifstream f(fname);
  140. if (f)
  141. {
  142. Record r;
  143. string line;
  144. for (nrecs = 0; getline(f,line); ++nrecs)
  145. {
  146. if (!r.parse(line))
  147. return -1;
  148. db.push_back(r);
  149. }
  150. }
  151. }
  152. return nrecs;
  153. }
  154.  
  155. int PlainDb::save(const char* fname)
  156. {
  157. int nrecs = -1;
  158. if (fname)
  159. {
  160. ofstream f(fname,ios::ate|ios::trunc);
  161. for (nrecs = 0; nrecs < size(); ++nrecs)
  162. {
  163. f << db[nrecs].toString() << "\n";
  164. if (f.bad())
  165. return nrecs?-nrecs:-1;
  166. }
  167. f.flush();
  168. }
  169. return nrecs;
  170. }
  171.  
  172. void dbTest(const string& dbname)
  173. {
  174. PlainDb db;
  175.  
  176. if (db.load(dbname) <= 0)
  177. return;
  178.  
  179. int i = db.findByName("Jesus");
  180. if (i >= 0)
  181. {
  182. db[i].setName("Maria");
  183. db[i].setAge(18);
  184.  
  185. db.save(dbname);
  186. }
  187. }
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: plotting cpu and mem consumption
Next Thread in C++ Forum Timeline: HELP ME MY MISTAKE and HELP THE CORRECT The my homework





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC