Hello,
I wrote a program to learn a thing or two about files.
I don't understand why I need to call tellg() or tellp() in every loop. I have noticed that these pointers keep track of file reading and writing, but as soon as no tellg() or tellp() is called, the file doesn't parse all the way.
listing 1 is the .cpp.
listing 2 is the input file, spellchecker.txt.
listing 3 is the console output of .cpp with line 51 commented.
listing 4 is the console output with tellg() called at line 51.
Please note, after "listing 3" spellechecker.txt was unmodified. After "listing 4" the file is modified (not as intended, but close enough).
/*
*spellchecker.cpp
*28.07.2011
*
* 1. take an ugly text file and insert spaces after point marks.
* 2. make all the letters following the point marks in uppercase.
*
*/
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main(int argc, char** argv)
{
cout << endl << endl;
cout << "\n spellchecker program \n";
fstream file1;
file1.open("spellchecker.txt");
if (file1.is_open() )
{
char char1; // current character in file
bool passed_period = 0; // used to determine the first lowercase char after a period.
while ( !file1.eof() )
{
file1 >> char1;
{
if ( char1 == '.' ) // insert a space after period
{
passed_period = 1;
if ( file1.tellp() != -1 )
file1<<' ';
}
if ( passed_period && ( char1 >= 97 && char1 <= 122 ) ) // if first lowercase char after period
{
if ( file1.tellp() != -1 )
{
file1<<(char)(char1 - 32);
}
passed_period = 0;
}
cout << " " <<char1;
}
file1.tellg(); // <-----------------?
}
file1.close();
}
else
cout << "\n spellcheck error: unable to open file";
cout << endl << endl;
return 0;
}
spellchecker.txt:
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
test.test.test.test.test test test. test test .test
line 51 commented:
spellchecker program
t e s t . .
line 51 uncommented:
spellchecker program
t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t e s t . e t . e t . e t . e t t e s t t e s t . t s t t e s t . e t t