fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5. // player node for linkedlist
  6. class Player {
  7. public:
  8. int id;
  9. string name;
  10. string position;
  11. int age;
  12. double salary;
  13. Player* next;
  14. };
  15. // player linkedlist
  16. class team {
  17. public:
  18. int rank;
  19. string name;
  20. string president;
  21. Player* head;
  22. // function to insert newnode(add new player)
  23. void addPlayer(int id, string name, string position, int age, double salary) {
  24. Player* newPlayer = new Player();
  25. newPlayer->id = id;
  26. newPlayer->name = name;
  27. newPlayer->position = position;
  28. newPlayer->age = age;
  29. newPlayer->salary = salary;
  30.  
  31. if (head == NULL) {
  32. head = newPlayer;
  33. } else {
  34. Player* temp = head;
  35. while (temp->next != NULL) {
  36. temp = temp->next;
  37. }
  38. temp->next = newPlayer;
  39. }
  40. }
  41.  
  42. void readTeamFromFile( string fileName) {
  43. ifstream inputFile(fileName);
  44.  
  45. if (!inputFile.is_open()) {
  46. cout << "Unable to open file "<< endl;
  47. return;
  48. }
  49.  
  50. string line;
  51. while (getline(inputFile, line)) {
  52. // Find positions of commas
  53. /*19,nada mohamed
  54.   pos1 -> 1->9->, =2;
  55.   pos2->1->9->,->n->a->d->a->space->m->o->h->a->m->e->d->,=15
  56.   */
  57. size_t pos1 = line.find(",");
  58. size_t pos2 = line.find(",", pos1 + 1);
  59. size_t pos3 = line.find(",", pos2 + 1);
  60. size_t pos4 = line.find(",", pos3 + 1);
  61. // Extract data from the line
  62. /*pos1+1 skip first comma 19|,n/ada
  63.   pos1=| & pos1+1=/ , pos2-pos1 find space between tow comma & -1 without second comma*/
  64. int id = stoi(line.substr(0, pos1));//stoi convert string into int num
  65. string name = line.substr(pos1 + 1, pos2 - pos1 - 1);
  66. string position = line.substr(pos2 + 1, pos3 - pos2 - 1);
  67. int age = stoi(line.substr(pos3 + 1, pos4 - pos3 - 1));
  68. double salary = stod(line.substr(pos4 + 1));
  69.  
  70. // Add the player to the linked list
  71. addPlayer(id, name, position, age, salary);
  72. }
  73.  
  74. inputFile.close();
  75. }
  76.  
  77. void displayPlayers() {
  78. Player* temp = head;
  79. if (temp==NULL) {
  80. cout << "No players in the team." << endl;
  81. return;
  82. }
  83.  
  84. while (temp) {
  85. cout << temp->id << "," << temp->name<< "," << temp->position << "," << temp->age << "," << temp->salary << endl;
  86. temp = temp->next;
  87. }
  88. }
  89. };
  90.  
  91. int main() {
  92. team team;
  93. team.name = "el bank el-ahly";
  94. team.readTeamFromFile("El Bank Al-ahly.txt");
  95. cout << "Players in team " << team.name << ":\n";
  96. team.displayPlayers();
  97.  
  98. return 0;
  99. }
  100.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Unable to open file 
Players in team el bank el-ahly:
No players in the team.