[Solved] Read strings into dynamically allocated array [closed]


It would be done musch simpler if you would use standard class std::string.
If to speak about character arrays then the approach is to allocate a character array of a fixed size. When there will be entered more characters than the size of the array then reallocate the array increasing its size and copy elements of the current array in the new one.

For example

const size_t N = 10;

char *s = new char[N];

char c;
size_t size = N;
size_t i = 0;

while ( std::cin >> c && c != '!' )
{
    if ( i == size - 1 )
    {
        char *p = new char[size + N];
        std::copy( s, s + size - 1, p );
        delete []s;
        s = p;
        size += N;
    }

    s[i++] = c;
}
   .

s[i] = '\0';

4

solved Read strings into dynamically allocated array [closed]