// File: io5.C // // Demonstrating simple I/O in C++ // Reading an arbitrarily long string #include #include // for endl, setw(), etc #include // for INT_MAX constant, etc #include // for NULL, EOF, etc // Function Prototype char *GetLine() ; char *GetLine() { char *str, *newstr ; const int INITLEN=5 ; int ch, i=0, j, len, newlen ; // initialize str to default length len = INITLEN ; str = new char[len] ; if (str == NULL) { cerr << "Out of Memory Error in GetLine: 0" << endl ; exit(1) ; } // keep reading until done // loop invariants: // i = index of new char. // always have room for one more character. while(true) { ch = cin.get() ; if (ch == EOF || ch == '\n') break ; if (i > len - 2) { // get more space? // double the length of new space. // newlen = 2 * len ; newstr = new char[newlen] ; if (newstr == NULL) { cerr << "Out of Memory Error in GetLine: 1" << endl ; exit(1) ; } // copy old data to new location // for (j = 0 ; j < i ; j++) { newstr[j] = str[j] ; } delete [] str ; str = newstr ; len = newlen ; } str[i] = ch ; i++ ; } str[i] = '\0' ; // Don't worry about exact fit for short strings or // strings that are almost full // if (len == INITLEN || i >= 0.75 * len) { return str ; } // Get block of memory that is an exact fit. // newlen = i+1 ; newstr = new char[newlen] ; if (newstr == NULL) { cerr << "Out of Memory Error in GetLine: 2" << endl ; exit(1) ; } // Copy data to new location // for (j = 0 ; j < newlen ; j++) { newstr[j] = str[j] ; } delete [] str ; return newstr ; } main() { char *p ; cout << "Enter string: " ; p = GetLine() ; cout << "You entered: " ; cout << p << endl ; }