I am writing code for a coding class, and I am writing a class called MyString which is supposed to be able to store a dynamic char array that acts like a String. However, when writing a read() function that is meant to act like the getline() function, I ran into an error after calling getline() with an istream object. After the call, the istream object was no longer good, and I could not figure out why. Any help/ideas would be appreciated.
Here is the erroring method of the MyString.cpp file:
//Copys contents of in into calling object up to when the deliminator is found in in
void MyString::read(istream& in, char deliminator)
{
char copyString[MyString::MAX_INPUT_SIZE];
if (in.good())
{
cout << "pre:all good" << endl;
}
else
{
cout << "pre:all bad" << endl;
}
in.getline(copyString, deliminator);
if (in.good())
{
cout << "post:all good" << endl;
}
else
{
cout << "post:all bad" << endl;
}
delete[]theString;
theString = new char[strlen(copyString) + 1];
strcpy(theString, copyString);
}
Here is the part of my main function that is calling that my read() method:
cout << endl << "----- now, line by line" << endl;
ifstream in2("mystring.txt");
assert(in2);
while (in2.peek() == '#') {
in2.ignore(128, '\n');
}
if (in2)
{
cout << "in2 is good!" << endl;
}
s.read(in2, '\n');
while (in2) {
cout << "in2 is still good: " << in2.good() << endl;
cout << "Read string = " << s << endl;
s.read(in2, '\n');
}
in2.close();
Here is the text file:
# This file has some strings that are used in the string test to check
# reading strings from files. The default overloaded >> of your string
# class should skip over any leading spaces and read characters into
# the string object, stopping at the first whitespace character (this is
# similar to the behavior of >> on char *). The read method of the
# string class is a little fancier. It allows client to restrict
# how many characters at max to read and what character to use as
# delimiter, so you can stop at newline instead of space, for example.
# Reading consumes the delimiting character, so the next read starts
# after that.
#
The first time we will
read individual words, next
we read whole lines
I tried fidgeting around with my parameter, and changing istream to ifstream, but it did nothing. I added the cout statements to test where the fault code was, and once I found that it was the in.getline() statement that was making the istream go bad, I tried looking up my problem from there. I couldn't find anything on this problem despite someone definitely also running into this before. ny help or ideas would be greatly appreciated.