'C++ Read txt and put each line into Dynamic Array

I am trying to read input.txt file, and trying to put each line into the array as string (later on I will use each element of array in initializing obj that's why I am putting each line into the array).

    string* ptr = new string;
    
    // Read Mode for Input
    fstream input;
    input.open("input.txt", ios::in);

    int size = 0;

    if (input.is_open()) {
        string line;
        while (getline(input, line)) {
            cout << line << endl;
            ptr[size] = line;
            size++;
        }
        input.close();
    }

    for (int i = 0; i < size-1; i++) {
        cout << "array: " << ptr[i] << endl;
    }

I am getting error as:

Proxy Allocated, drain it



Solution 1:[1]

As was noted in the comments, if you don't know how many lines in the file then you need a container which grows on request at runtime. The natural choice is std::vector :

std::fstream input("input.txt", std::ios::in);

std::vector<std::string> lines;
std::string line;
while (getline(input, line)) {
  lines.push_back(line);  // std::vector allocates more memory if needed
}

for (int i = 0; i < lines.size(); i++) {
  std::cout << lines[i] << std::endl;
}

Solution 2:[2]

Don't use arrays; use std::vector. The std::vector behaves like an array and uses Dynamic Memory:

std::string s;
std::vector<std::string> database;
while (std::getline(input, s))
{
    database.push_back(s);
}

Keep it simple. :-)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Thomas Matthews