I have a very similar assignment in which we have been specified that we are NOT allowed to use vectors. Is there any other way in this case to count the number of lines of data within a text file??

If you are not allowed to use vector then you will have to read the entire file, counting the line numbers as the loop progresses. There is no other way to do it.

Why do you need the line count? Maybe there are alternative ways to achieve what you want to do.

If you are not allowed to use vector then you will have to read the entire file, counting the line numbers as the loop progresses. There is no other way to do it.

Why do you need the line count? Maybe there are alternative ways to achieve what you want to do.

I have to use a dynamic array structure to store the contents of a an input text file. Firstly I do not know how long the input text file will be and thus need to work this out first. The use of a dynamic array is also necessary as we are required to be able to insert and delete elements from the array. Also I am having problems with storing strings into my array as I only know how to store integers. Could you help with this at all? Thanks!

You could use malloc() and realloc() to allocate space for the array. One way to do it is to allocate one row in the array each time a new line is read from the file. But that is slow and inefficient. I prefer to allocate a block of rows and when they get filled up inreeast the array by another block of rows.

char** array = 0; // 2d array of strings
int arraysize = 0; // current number of rows in the array
int elmsused = 0; // number of rows actually used
const int BLOCKSIZE = 10;

string line;
ifstream in("file.txt");
while( getline(in, line) )
{
      if( elmsused == arraysize)
      {
             array = (char **)realloc(array, arraysize+BLOCKSIZE);
             arraysize += BLOCKSIZE);
      }
      array[elmsused] = (char *)malloc(line.size()+1);
      strcpy(array[elmsused], line.c_str());
      elmsused++;
}

}

This article has been dead for over six months. Start a new discussion instead.