tags:

views:

65

answers:

2

Here is a simple code to print all characters of a txt file on screen:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
       int **i;
       int j,k;
       char a;
    ifstream test("test.txt", ios::binary);
    while((a=test.get())!=-1)//if I use "while(!test.eof())" here, how to avoid the output of the last character(-1) to std::cout, or any ostream objects?
    {
   putchar(a);//also change this to putchar(test.get());
    }
       getchar();
}

As I noted in the code, if I use "test.eof()" to judge the end of test.txt, I'll always get an extra blank at the end of the output. How to avoid it?

+1  A: 

You want:

int a;

The get() function returns an int, not a char - this is the same in C - when using getchar(), you read into an int variable not char. So your loop looks like:

while( ( a = test.get() ) != EOF )

note you want EOF here, not eof(). a version using eof() would look like this:

char c;
while( test.get( c ) ) {
   putchar( c );   // or whatever
}

if ( test.eof() ) {
  // Ok, we finished because of end of file
}
else {
  // finished not because of end of file - probably an error
}
anon
Yes I know get() returns an int, and EOF equals to -1.But what I want to know is when using istream::eof(), how to show the file correctly?
L.Lawliet
@LLawler If you know that,. why didn't your code use an int? I've posted an example which uses eof() - note it is a Bad Idea to loop on eof() - it is only intended for diagnosing the stream state after a read failed.
anon
OK. I understand you now. But I'm wondering why you insisted I use an int? The char type can also be assigned an int value and compared with -1.
L.Lawliet
@L.Lawliet You are reading a binary file. If you use a char variable, the first time a byte with the value of 0xff is read (assuming char is signed, which is unspecified in C++) your loop will terminate. That's why in both C and C++ functions like get() and getchar() return an int.
anon
Thank you so much! I ignored this 0XFF! I'm a rookie in reading files...
L.Lawliet
A: 

the get method will only set the eof error bit after an attempt to read past the EOF. That's why you get the extra blank with the while (!test.eof()) case. Generally you always have to read past the EOF before detecting that an EOF occurred. Maybe you could do it like this:

char c = test.get();
while (!test.eof()) {
    putchar(c);
    c = test.get();
}

or rewritten as for:

for (char c = test.get(); !test.eof(); c = test.get()) {
    putchar(c);
}
king_nak
Yeah this is another solution. But is it dispensable to add a variable here? If I just want to use putchar(test.get()) to print every character and don't feel like any other intermediate , any good advice?
L.Lawliet