avr39ripe

cppStrDynArrContainer

Oct 14th, 2021
793
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3.  
  4. int main()
  5. {
  6.     const int maxLines{ 100 };
  7.     const int maxLen{ 5 };
  8.  
  9.     //char text[maxLines][maxLen]; // memory used = 20000 bytes
  10.     char* text[maxLines]{}; // memory used sizeof(char*) * maxLines = 4 * 100 = 400 bytes
  11.  
  12.     //char* buf{ new char[maxLen] };
  13.     char buf[maxLen];
  14.     int memoryUsed{ 0 };
  15.     char menu{ 'Y' };
  16.     int textPos{};
  17.     int strLength{};
  18.  
  19.     std::cout << "Enter text lines one by one, max 199 chars long:\n";
  20.  
  21.     do
  22.     {
  23.         std::cout << textPos << ": ";
  24.         std::cin.getline(buf, maxLen - 1);
  25.  
  26.         if (std::cin.fail())
  27.         {
  28.             std::cin.clear();
  29.             std::cout << "Too long line!\n";
  30.             //std::cin.ignore(32768, '\n');
  31.         }
  32.  
  33.         strLength = strlen(buf) + 1;
  34.         text[textPos] = new char[strLength];
  35.         strcpy_s(text[textPos], strLength, buf);
  36.         ++textPos;
  37.         memoryUsed += strLength;
  38.  
  39.         std::cout << "Enter one more string? y/n\n";
  40.         std::cin >> menu;
  41.         std::cin.ignore(100, '\n');
  42.  
  43.     } while ((menu == 'Y' or menu == 'y') and textPos < maxLines);
  44.  
  45.     for (textPos = 0; textPos < maxLines and text[textPos]; ++textPos)
  46.     {
  47.         std::cout << textPos << " : " << text[textPos] << '\n';
  48.         delete[] text[textPos];
  49.     }
  50.  
  51.     std::cout << "Memory used " << memoryUsed << '\n';
  52.  
  53.  
  54.     //delete[] buf;
  55.     return 0;
  56. }
RAW Paste Data