avr39ripe

cppPlayerStructBasics

Jun 22nd, 2021
798
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. const int maxNameLen{ 50 };
  5.  
  6. struct Player
  7. {
  8.     int id;
  9.     char* name{nullptr};
  10.     int rank;
  11.  
  12.     void init(int idP, const char* nameP, int rankP)
  13.     {
  14.         id = idP;
  15.  
  16.         setName(nameP);
  17.  
  18.         rank = rankP;
  19.     }
  20.  
  21.     void setName(const char* nameP)
  22.     {
  23.         auto len{ strlen(nameP) + 1 };
  24.  
  25.         if (!name)
  26.         {
  27.             name = new char[len];
  28.         }
  29.         else if (name and strlen(name) + 1 < len)
  30.         {
  31.             delete[] name;
  32.             name = new char[len];
  33.         }
  34.  
  35.         strcpy_s(name, len, nameP);
  36.     }
  37.  
  38.     void print()
  39.     {
  40.         std::cout << id << ' ' << name << ' ' << rank << '\n';
  41.     }
  42.  
  43.     void clear()
  44.     {
  45.         delete[] name;
  46.     }
  47. };
  48.  
  49. void printPlayers(Player* begin, Player* end)
  50. {
  51.     for (auto player{ begin }; player != end; ++player)
  52.     {
  53.         player->print();
  54.     }
  55. }
  56.  
  57. void clearPlayers(Player* begin, Player* end)
  58. {
  59.     for (auto player{ begin }; player != end; ++player)
  60.     {
  61.         player->clear();
  62.     }
  63. }
  64.  
  65. int main()
  66. {
  67.     const int playersCount{ 3 };
  68.     Player players[playersCount];
  69.     Player* const playersEnd{ players + playersCount };
  70.  
  71.     players[0].init(26007, "MadMax", 39);
  72.     players[1].init(28002, "Batman", 25);
  73.     players[1].setName("MishMans");
  74.     players[2].init(29002, "Joker", 15);
  75.  
  76.     //players[0].print();
  77.     //players[1].print();
  78.     //players[2].print();
  79.     printPlayers(players, playersEnd);
  80.  
  81.     //players[0].clear();
  82.     //players[1].clear();
  83.     //players[2].clear();
  84.     clearPlayers(players, playersEnd);
  85.  
  86. };
  87.  
RAW Paste Data