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?
You want:
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:
note you want EOF here, not eof(). a version using eof() would look like this: