I've finished and turned in my myString class. The prof gave us a test harness to run against our class, so we can make corrections and turn it back in. Everything else works fine, but I have come across a problem with my getline() function. It seems to work fine when reading from the keyboard, but doesn't work when reading from a file.
This is what the function is right now.
1 2 3 4 5 6 7 8 9 10 11 12
|
void getline(std::istream& ins, mystring& target)
{
mystring tempstring;
char ch;
while (ins.peek()!='\n')
{
ins.get(ch);
tempstring+=ch;
}
target=tempstring
}
|
The file it reads from is simple, just two lines:
1 2
|
This is line 1.
This is line 2.
|
This is the code he uses to read the file with getline():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
// Open the file for the first set of tests
fin.open("mystringtest.txt");
fin.clear();
if(fin.fail()) {
cout << "Problem opening \"mystringtest.txt\"" << endl;
cout << "file i/o tests skipped." << endl;
} else {
// Testing fin >> into an empty string
while(fin >> s1) {
cout << s1.toString();
} // while
fin.close();
cout << "\n8.5\tTesting getline(fin,s1);" << endl;
fin.open("mystringtest.txt");
fin.clear(); // clear eof flag since open doesn't do so automatically
while(!fin.eof()) {
getline(fin,s1);
cout << s1.toString();
} // while
} // if
|
The problem is that it reads in the first line just fine, then goes into a continuous loop(It never gets to the second line, which I think is because of the newline character at the end of the first line. If I put a cin.ignore(1,'\n') at the end, it outputs the first line, clears the newline character, then reads in the second line just fine, then sits there. I think in this case, the ignore also clears the 2nd newline of the file, and it never hits the EOF.
Any ideas?