/* * Note to CS70 students: this file contains a really stupid (and * somewhat unreliable) readString function, which you can use to help * debug your assignment. However, before submitting, you must * replace this function with your own readString from homework #3. */ /* * Name: Geoff Kuenning * Course: CS 70, Spring 2000 * Assignment #4 * * This file contains the implementation of the readString function. * See below or the header file "readstring.hh" for a full description * of what the function does. Basically, it reads and returns strings * of non-whitespace characters of arbitrary length, returning NULL * when EOF is encountered. */ #include #include #include "readstring.hh" /* * Table of contents: the following routines are defined in this file */ char* readString(istream& stream); // Read and return a non-white string /* * Size of the maximum readable string. */ const int MAX_STRING = 20; /* * readString function * * This function accepts an istream and returns a C-style string read * from that string, under the following conditions: * * 1. If EOF has already been encountered, or if EOF is * encountered before any nonwhite characters are reached, * NULL is returned. * 2. The returned string consists solely of nonwhite characters, * as defined by the iswhite() function in ctype.h. * 3. Leading whitespace is skipped on the stream to reach * nonwhite characters. Trailing whitespace (after the * string) is not disturbed. * 4. The returned string is null-terminated. * 5. The returned string may not be longer than 20 characters. * 6. The returned string is allocated using "new[]", and the * caller is responsible for delete[]-ing the space when it is * no longer needed. */ char* readString( istream& stream) // Stream to read from { /* * If we hit EOF last time, don't try to read any more. */ if (!stream) return NULL; /* * Allocate space for the string and the null byte. */ char* string = new char[MAX_STRING + 1]; /* * The built-in >> function will read into the string. */ string[0] = '\0'; stream >> string; /* * Check for EOF */ if (!stream && string[0] == '\0') { delete[] string; return NULL; } /* * Since we actually read something, we must remove any EOF * indication so that anybody else who tests the stream won't see * the EOF until the next time they read from it. This isn't * strictly necessary, since the caller should be using the NULL * return to test for EOF, but it makes me feel better and it'll * make it easier to convert this routine into a >> operator * later. * * Unfortunately, the method for clearing the EOF is a bit of magic. */ if (!stream.good()) stream.clear(stream.rdstate() & ~ios::failbit); return string; }