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
CodePudding user response:
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. :-)
CodePudding user response:
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;
}