fstream::get(char&) repeating last character

K

kieran

Hi,
I'm using fstream.get to read in a character from a file, then print it
on the screen. I have a file called test.log that contains "Hello,
World!", but when I try and print the contents out on the screen I get
"Hello, World!!". The following is the code (please ignore all
wxWidgets classes):

void SystemBackupFrm::compress()
{
using namespace std;
const wxString dir = "C:\\Backups\\";

wxFFileOutputStream out(dir + "files.zip");
wxZipOutputStream zip(out);
wxTextOutputStream data(zip);


fstream file1("C:\\test.log", ios::in );
zip.PutNextEntry("C:\\test.log");
char t;


while(file1.good())
{
file1.get(t);
cout << t ;
data << t;
}
file1.close();

}

Cheers,
Kieran
 
A

Alf P. Steinbach

* (e-mail address removed):
I'm using fstream.get to read in a character from a file, then print it
on the screen. I have a file called test.log that contains "Hello,
World!", but when I try and print the contents out on the screen I get
"Hello, World!!". The following is the code (please ignore all
wxWidgets classes):

[extranous code removed]
void SystemBackupFrm::compress()
{
using namespace std;
fstream file1("C:\\test.log", ios::in );

Strong hint: make that

"c:/test.log"

Windows accepts both forward and backward slash at the API level.
You only need those awkward backward slashes for the user interface,
and then only if you elect to uphold the illusion of backslashisism.
With forward slash you can use a single convention throughout the
C++ code, especially in #include directives.
char t;

while(file1.good())
{
file1.get(t);
cout << t ;
}
file1.close();
}

When 'get' fails you still output the the content of 't', which
hasn't been changed.
 
K

kieran

Thanks,
I stupidly thought it was something to do with fetching the character
itself. Also thanks for the advice on forward and back slashes,
Cheers,
Kieran
 
J

Jon Bell

while(file1.good())
{
file1.get(t);
cout << t ;
data << t;
}

good() returns "false" only *after* you have *tried* and *failed* to read
past the end of the file. A correct way to write your input loop is as
follows:

while (file1.get(t))
{
cout << t;
data << t;
}

In a boolean context, get() (like all other standard C++ input operations)
evaluates as "true" if the input succeded, and "false" if it failed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top