C++ Reading from a text file

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: May 2007
Posts: 7
Reputation: rockthrower is an unknown quantity at this point 
Solved Threads: 0
rockthrower rockthrower is offline Offline
Newbie Poster

Re: C++ Reading from a text file

 
0
  #11
May 15th, 2007
OK, so this program that I am writing basically reads data from a text file then stores the data into an array of objects - one object per line. It then makes the necessary calculations and outputs the results to a file. I managed to get the program to work but I still have problems reading in the data.

Firstly, I am currently taking in the names in the text file into a string and the problem with this is when there is a name with a format such as: "J. p morgan" because i have set aside only two strings, one for the first name and one for the second name, and so when the program attempts to read such a name, the next line is not read in correctly.

Also, for some reason I am not able to read in the full double amount such as 45.55. only 45.5 is stored and not the entire amount although I am using a double variable to store it.

And finally, the last lines in each list is stored twice for some reason in my output file.

So the bottomline is that I need a consistent and efficient way of reading in an entire line from the text file correctly.

I am reading in from two seperate files, one file has the following format:

5 Christine Kim 30.00 2 1 F
15 Ray Allrich 10.25 0 0 M
16 Adrian Bailey 12.50 0 0 F
17 Juan Gonzales 30.00 1 1 M
18 Morris Kramer 8.95 0 0 M
22 Cindy Burke 15.00 1 0 F
24 Esther Bianco 10.25 0 0 F
25 Jim Moore 27.50 3 1 M
32 Paula Cameron 14.50 0 0 F
36 Melvin Ducan 10.25 0 0 M
37 Nina Kamran 30.00 1 1 F
38 Julie Brown 35.00 0 1 F
40 Imelda Buentello 14.50 0 0 F
43 Maria Diaz 15.00 0 0 F
42 J. P. Morgan 12.50 0 0 M

So for example, if the line is "42 J. P. Morgan 12.50 0 0" I need to extract "42", "J. P. Morgan", "12.50", "0", "0"

The other text file has this format:

17 20.0
37 31.0
5 40.0
42 39.5
24 15.0
22 40.0
15 42.0
18 40.0
25 45.0
32 25.0
40 47.5
36 -40.0
16 40.0
38 35.0
43 40.0
33 30.0

This is my entire code:

  1.  
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <string>
  5. #include <fstream>
  6. using namespace std;
  7. //Class
  8. class EmpInfo
  9. {
  10. private:
  11. int empId; // Used to store employee id
  12. char empName[21]; // Used to store employee name
  13. double empPayrate; // Used to store employee's pay rate
  14. int empDep; // Used to store employee's dependents
  15. int empType; // Used to store employee type
  16.  
  17. public:
  18. EmpInfo();
  19. EmpInfo(int, char[], double, int, int);
  20. void set(int, char[], double, int, int);
  21. int getID();
  22. const char *getName();
  23. double getPayrate();
  24. int getDep();
  25. int getType();
  26.  
  27.  
  28. }; // End of class
  29. EmpInfo::EmpInfo()
  30. {
  31. empId = 0;
  32. strcpy( empName, "");
  33. empPayrate = 0.0;
  34. empDep = 0;
  35. empType = 0;
  36. }
  37. EmpInfo::EmpInfo(int Id, char name[], double rate, int dep, int type)
  38. {
  39. set(Id, name, rate, dep, type);
  40. }
  41. void EmpInfo::set(int Id, char name[], double rate, int dep, int type)
  42. {
  43. empId = Id;
  44. strcpy(empName, name);
  45. empPayrate = rate;
  46. empDep = dep;
  47. empType = type;
  48. }
  49. int EmpInfo::getID()
  50. {
  51. return empId;
  52. }
  53. const char *EmpInfo::getName()
  54. {
  55. return empName;
  56. }
  57. double EmpInfo::getPayrate()
  58. {
  59. return empPayrate;
  60. }
  61. int EmpInfo::getDep()
  62. {
  63. return empDep;
  64. }
  65. int EmpInfo::getType()
  66. {
  67. return empType;
  68. }
  69. const int MAX_EMP = 100; // Max number of employees
  70. int search(int, EmpInfo[], int);
  71. double printReport(int, EmpInfo[], ofstream&, int);
  72. double calcGrosspay(int, EmpInfo[], int);
  73. int main()
  74. {
  75. EmpInfo Emp[MAX_EMP]; // Declare array of structs
  76. int numEmp; // employees counter
  77. int transNum; // transaction counter
  78. ifstream empFile; // Establish input file stream
  79. ofstream outputFile; // Establish output file stream
  80. string firstName; // Used to extract employee's first name
  81. string lastName; // Used to extract employee's first name
  82. string tempName; // Store first and last name
  83. int id; // Used to store employee id
  84. char name[21]; // store name in character array to send to object class
  85. double rate; // Used to store employee's pay rate
  86. int dep; // Used to store employee's dependents
  87. int type; // Used to store employee type
  88. int hours; // Number of hours worked by employee
  89.  
  90. //Open employee file
  91. empFile.open("master.txt");
  92.  
  93. //Make sure file exists/opens
  94. if (!empFile)
  95. {
  96. cout << "Can not open employee file \"master.txt\"" << endl;
  97. return 1;
  98. }
  99.  
  100. numEmp = 0;
  101. empFile >> id;
  102. empFile >> firstName >> lastName; // Extract first and last name
  103. tempName = firstName + " " + lastName; // Concantinate both names
  104. tempName.copy(name, 21, 0); // Copy string into array called name
  105. empFile >> rate >> dep >> type;
  106. empFile.ignore(999, '\n');
  107.  
  108. while (empFile && numEmp < MAX_EMP)
  109. {
  110. // Move new employee info into array and increment numEmp count
  111. Emp[numEmp].set(id, name, rate, dep, type);
  112. numEmp++;
  113.  
  114. // Get next employee info
  115. empFile >> id;
  116. empFile >> firstName >> lastName; // Extract first and last name
  117. tempName = firstName + " " + lastName; // Concantinate both names
  118. tempName.copy(name, 21, 0); // Copy string into array called name
  119. empFile >> rate >> dep >> type;
  120. empFile.ignore(999,'\n');
  121. }
  122.  
  123. empFile.clear();
  124. //close masterfile
  125. empFile.close();
  126.  
  127. // open transaction file
  128. empFile.open("trans.txt");
  129.  
  130. //Make sure file exists/opens
  131.  
  132. transNum = 0;
  133. empFile >> id;
  134. empFile >> hours;
  135. empFile.ignore(999,'\n');
  136.  
  137. // output invalid transactions
  138. outputFile.open("report.txt");
  139.  
  140. // Print header to file
  141. outputFile << setw(10) << "ID:" << setw(20) << "NAME:" << setw(10) << "TAX:"
  142. << setw(15) << "INSURANCE:" << setw(15) << "GROSS PAY:" << setw(15) << "NET PAY:" << endl;
  143. outputFile << setw(10) << "---" << setw(20) << "-----" << setw(10) << "----" << setw(15) << "----------"
  144. << setw(15) << "----------" << setw(15) << "--------" << endl;
  145.  
  146. // Print Error and Control Report Header
  147. cout << "INVALID TRANSACTIONS:" << endl;
  148. cout << "---------------------" << endl;
  149. cout << endl;
  150. cout << setw(5) << "ID:" << setw(15) << "HOURS:" << endl;
  151. cout << setw(5) << "---" << setw(15) << "------" << endl;
  152.  
  153. int correct;
  154. double netPayTotal;
  155. double grossPayTotal;
  156. while (empFile && transNum < MAX_EMP)
  157. {
  158. // search to see if id is valid
  159. int check = search(id, Emp, MAX_EMP);
  160.  
  161. if(check != -1 && hours >= 0)
  162. {
  163. netPayTotal += printReport(check, Emp, outputFile, hours);
  164. grossPayTotal += calcGrosspay(check, Emp, hours);
  165. correct++;
  166. }
  167.  
  168. else
  169. {
  170. cout << setw(5) << id << setw(15) << hours << endl;
  171.  
  172. }
  173. empFile >> id;
  174. empFile >> hours;
  175. empFile.ignore(999,'\n');
  176. transNum++;
  177.  
  178. }
  179.  
  180. cout << endl;
  181. cout << endl;
  182. // Print Error and Control Report Header
  183. cout << "VALID TRANSACTIONS:" << endl;
  184. cout << "-------------------" << endl;
  185. cout << endl;
  186. cout << setw(10) << correct << endl << endl;
  187.  
  188. outputFile << setw(70) << "----------" << setw(15) << "--------" << endl;
  189. outputFile << endl;
  190. outputFile << setw(55) << "Weekly Total:" << setw(15) << grossPayTotal << setw(15) << netPayTotal << endl;
  191. outputFile << setw(55) << "-------------" << endl;
  192.  
  193. // Close outputfile
  194. outputFile.close();
  195. // Close inputfile
  196. empFile.close();
  197.  
  198. system("PAUSE");
  199. return 0;
  200. }
  201.  
  202. int search(int val, EmpInfo list[], int length)
  203. {
  204. int index = 0;
  205. while(index < length)
  206. {
  207. if(val == list[index].getID())
  208. return index;
  209. index++;
  210. }
  211. return -1; // id not found
  212. }
  213.  
  214. double printReport(int index, EmpInfo Emp[], ofstream &outputFile, int hours)
  215. {
  216. double tax; // Tax amount for employee
  217. double insurance; // Insurance cost for each employee
  218. double grossPay; // Pay before insurance and tax
  219. double netPay; // Net pay
  220.  
  221. // Calculate grossPay
  222. grossPay = calcGrosspay(index, Emp, hours);
  223.  
  224. // Calculate tax
  225. tax = grossPay * 0.15;
  226. // Calculate insurance
  227. insurance = 20.00 * Emp[index].getDep();
  228. // Calculate netpay
  229. netPay = ((grossPay - tax) - insurance);
  230.  
  231. // Output to file
  232. outputFile << setw(10) << Emp[index].getID() << setw(20) << Emp[index].getName()
  233. << setw(10) << setprecision(2) << fixed << tax << setw(15) << setprecision(2)
  234. << fixed << insurance << setw(15) << setprecision(2) << fixed << grossPay
  235. << setw(15) << setprecision(2) << fixed << netPay << endl;
  236.  
  237. return netPay;
  238.  
  239. }// End of printReport function
  240.  
  241. double calcGrosspay(int index, EmpInfo Emp[], int hours)
  242. {
  243. double grossPay;
  244. // If management employee or if hours <= 40
  245. if (Emp[index].getType() == 1 || hours <= 40)
  246. {
  247. grossPay = (hours * Emp[index].getPayrate());
  248.  
  249. }
  250. // If non-management employee or hours > 40
  251. else
  252. {
  253. grossPay = ((40 * Emp[index].getPayrate()) + ((hours - 40) * 1.5 * Emp[index].getPayrate()));
  254.  
  255. }
  256. return grossPay;
  257.  
  258. } // End of calcGrosspay functions
Last edited by rockthrower; May 15th, 2007 at 5:10 am.
Reply With Quote Quick reply to this message  
Join Date: May 2006
Posts: 3,124
Reputation: WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of 
Solved Threads: 283
Moderator
WaltP's Avatar
WaltP WaltP is offline Offline
Posting Sensei

Re: C++ Reading from a text file

 
0
  #12
May 16th, 2007
First of all, please format your code. It's nearly impossible to follow.

Originally Posted by rockthrower View Post
Firstly, I am currently taking in the names in the text file into a string and the problem with this is when there is a name with a format such as: "J. p morgan" because i have set aside only two strings, one for the first name and one for the second name, and so when the program attempts to read such a name, the next line is not read in correctly.
You can't use >> when reading a file with evil syntax like you have. Read an entire line using getline() and write a function to pull out and convert all the bits and pieces by looking at the line character by character.

Originally Posted by rockthrower View Post
And finally, the last lines in each list is stored twice for some reason in my output file.
Generally this is a problem with using .eof() when you loop through the file for reading. This is what happens, feof() is identical to .eof().
The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 7
Reputation: rockthrower is an unknown quantity at this point 
Solved Threads: 0
rockthrower rockthrower is offline Offline
Newbie Poster

Re: C++ Reading from a text file

 
0
  #13
May 16th, 2007
Thanks for the tips!

I am needing to use a pointer to an array of objects in addition to dynamically allocating memory for the array of objects. For some reason, I keep getting error messages:

  1.  
  2. while (empFile && transNum < empCount)
  3. {
  4. // search to see if id is valid
  5. check = search(id, Emp, empCount);
  6.  
  7. [COLOR=red]"cannot convert `EmpInfo*' to `EmpInfo**' for argument `2' [/COLOR]
  8. [COLOR=red]to [/COLOR][COLOR=red]`int search(int, EmpInfo**, int)' "[/COLOR]
  9.  
  10. // If ID and hours are both valid
  11. if(check != -1 && hours >= 0)
  12. {
  13. // Calculate netpay total
  14. netPayTotal += printReport(check, Emp, outputFile, hours);
  15.  
  16. [COLOR=red]"cannot convert `EmpInfo*' to `EmpInfo**' for argument [/COLOR]
  17. [COLOR=red]`2' to `double printReport(int&, EmpInfo**, std::ofstream&, [/COLOR]
  18. [COLOR=red]int&)' " [/COLOR]
  19.  
  20. // Calculate grosspay total
  21. grossPayTotal += calcGrosspay(check, Emp, hours);
  22.  
  23. [COLOR=red]"cannot convert `EmpInfo*' to `EmpInfo**' for argument [/COLOR]
  24. [COLOR=red]`2' to `double calcGrosspay(int&, EmpInfo**, int*)' "[/COLOR]
  25.  
  26. correct++; // Increment number of correct transactions counter
  27. }
  28.  
  29. // If ID or hours not valid print out the id and hours
  30. else
  31. {
  32. cout << setw(5) << id << setw(15) << hours << endl;
  33.  
  34. }
  35. empFile >> id; // read in ID
  36. empFile >> hours; // read in hours
  37. empFile.ignore(999,'\n'); // ignore the rest of the line
  38. transNum++; // increment counter
  39.  
  40. }
Last edited by rockthrower; May 16th, 2007 at 5:44 am.
Reply With Quote Quick reply to this message  
Join Date: May 2006
Posts: 3,124
Reputation: WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of WaltP has much to be proud of 
Solved Threads: 283
Moderator
WaltP's Avatar
WaltP WaltP is offline Offline
Posting Sensei

Re: C++ Reading from a text file

 
0
  #14
May 17th, 2007
Please use the PREVIEW button before SUBMITting your post so you can see yourself if it's readable...

Your errors are telling you to look at the definition of the function and see what you should be passing, but you are not. You are passing a pointer when the function wants a pointer to a pointer
The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 14622 | Replies: 13
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC