Search code examples
c++arrayspointersdynamic-memory-allocation

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

  • 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. :-)