-2

I want to store lines from a file in an array and that's easy to do with a string:

std :: string query[100];

std::ifstream ifs(filename);

if (ifs.is_open())
{
    while (getline(ifs, query[size]))
    {
        size++;
    }
}

Problem is, I'm not allowed to use strings. How can I make this to work if query was a char* array?

Roxy
  • 132
  • 2
  • 9
  • `Problem is, I'm not allowed to use strings` -- Nothing would stop you from creating a simplified string class and use that instead. That's how you truly thwart restrictions like this. – PaulMcKenzie Nov 19 '16 at 15:50
  • 1
    Possible duplicate of [std::string to char\*](http://stackoverflow.com/questions/7352099/stdstring-to-char) – haider_kazal Nov 19 '16 at 17:52

1 Answers1

1

An easy way (but have limited capacity) is allocateing some buffer and reading data into it.

const int maxLength = 1024; // specify enough length
char* query[100];

std::ifstream ifs(filename);

if (ifs.is_open())
{
    while (ifs.getline(query[size] = new char[maxLength], maxLength))
    {
        size++;
    }
    delete[] query[size]; // delete buffer where data wasn't read
}

To avoid out-of-range access, the condition in while statement should be

while (size < sizeof(query)/(*query) && // size is less than number of elements in query
    ifs.getline(query[size] = new char[maxLength], maxLength))
MikeCAT
  • 73,922
  • 11
  • 45
  • 70