-1

I am relatively new to C++, and I am attempting to read sequenceofchars from a text file into a char array that is dynamically allocated. My code is as follows:

while (file.get(c))
{
    if (c =='\n')
        continue;

    char *temp = new char[i++];
    arrayA = new char[i++];
    arrayA[i] = c;
    delete [] arrayA;
    arrayA = temp;
}

And the text file format is as follows:

>NameOfChars
sequenceofchars

This is obviously horribly broken, but I've struggled to figure out the exact methodology one would use to go through this. I know about the Vector class, but I am unsure about how to go about using that if that is the preferred method for reallocating arrays on the heap. Any help would be greatly appreciated. Thank you.

trincot
  • 317,000
  • 35
  • 244
  • 286
tdark
  • 29
  • 5

2 Answers2

1

I think you should definitely take a look at the vector class since it would make your code a lot cleaner. Here is a small (untested) code sample of how to use it:

#include <vector>

std::vector<char> my_vector;

while (file.get(c))
{
    if (c =='\n')
        continue;

    my_vector.push_back(c);
}

For more information please check http://www.cplusplus.com/reference/vector/vector/push_back/

Hanna H
  • 120
  • 7
0

A raw array isn't dynamically allocated; hence using an STL container like vector would be better.

ifstream inf;
char c;
vector<char> charVec;

while (inf >> c)
{
    charVec.push_back(c);
}
Poriferous
  • 1,566
  • 4
  • 20
  • 33