My code opens a text file, counts the number of lines, allocates an array to store all lines and then calls a function to fill this array with each line. This function file.getline calls return empty strings:
Here’s the code:
typedef char* line;
…
char* filename=new char[256];
cout << "Type a file name: " << endl;
cin.ignore();
cin.getline(filename,255);
ifstream iFile(filename);
int nLines=CountLines(iFile);
line* LineArray = new line[nLines];
ReadLines(LineArray,iFile);
CountLines function:
int CountLines(ifstream &file)
{
line templine=new char[64];
int nLines=0;
while (!file.eof())
{
file.getline(templine,64);
if (*templine != '\n')
nLines++;
}
delete [] templine;
return nLines;
}
This works properly. ReadLines however does not:
void ReadLines(line* LineArray, ifstream &file)
{
line templine=new char[64];
file.seekg(0,ios::beg);
int i = 0;
while (!file.eof())
{
if (*templine != '\n')
{
LineArray[i]=templine;
i++;
}
}
delete [] templine;
}
I have a feeling that it has something to do with the ‘\n’ issue of getline but as I set the get pointer to 0 and the file starts with normal text and not a line, I can’t understand why it fills templine with empty strings.
There are too many bugs in your code.
istream::getline()is wrongCountLines()Pointers are not toys, you’d better go with Tino Didriksen’s solution.
If you really like char and pointers, it should look like this: