read message from a file

Hi,I'm new to c++ & programming

here,I have some questions about reading file

source code:


#include <fstream>
#include <iostream>
#include <string>
#include <cctype>

int main()
{
std::ifstream infile;
char letter;

infile.open("me.in");
do
{
infile.get(letter);
std::cout<<letter;
}while(infile);

std::cin.get();
return 0;
}


and me.in is below

hello world


But after I complied the code


The console show is different.



like hello worldd

could anyone tell me why?
in the loop:

get makes letter = 'h'
cout prints 'h'
all flags are ok so repeat

...

get makes letter = 'd'
cout prints 'd'
all flags ok

get tries to find a letter but finds the end of file
cout prints letter, which is still 'd'
eof flag is set
Do u mean the loop should be precondition style?


^_^ ?
1
2
3
4
5
while(true){
   infile.get(letter);
   if(!infile) break;
   std::cout << letter;
}
should work.
Thankyou!,It works well
1
2
while( infile.get(letter) )
  std::cout << letter;
It's prettier.
Topic archived. No new replies allowed.