#include #include #include // Read all of input into the memory. // Read each line into a string // allocate memory for the string // copy the string into that memory // add the newly allocated string // to an array of pointers int read_lines( char *lines[], int maxnlines ) { const int maxlinelen = 8000; char line[ maxlinelen ]; int nlines = 0; long total_bytes = 0; while ( std::cin.getline( line, maxlinelen ) ) { int len = std::cin.gcount(); // includes space for '\0' assert( len == strlen( line ) + 1 ); total_bytes += len; char *p; if ( nlines >= maxnlines || ( p = new char[ len ] ) == NULL ) { return -1; } else { strcpy( p, line ); lines[ nlines++ ] = p; } } std::cout << "allocated a total of " << total_bytes << '\n'; return nlines; } void write_lines( char *lines[], int nlines ) { while ( nlines-- > 0 ) std::cout << *lines++ << '\n'; } void free_lines( char *lines[], int nlines ) { while ( nlines-- > 0 ) delete [] *lines++; } int main( void ) { const int maxlines = 100; char *line[ maxlines ]; int nlines = read_lines( line, maxlines ); if ( nlines >= 0 ) { write_lines( line, nlines ); free_lines( line, nlines ); } else { std::cerr << "Input is too big to read\n"; } }