Problem in printing text file!

Hi there,
There is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void printfile(const list<char> &myList)
{
   list<char>::const_iterator itr;
   
   for (itr = myList.begin(); itr != myList.end(); itr++ ) {
      cout << *itr;
   }
   cout << "\n";
}

void getfile(list<char> &myList, const char *file)
{
   ifstream fin;
   char character;
   
   fin.open(file);
   if (!fin) {
      cout << "can't read " << file << "\n";
      exit(0);
   }
   
   while (!fin.eof()) {
      fin.get(character);
      myList.push_back(character);
   }
   fin.close();   
}


The problem is the output always has one more character as same as the last character in text file.
For example: "i have a mouse" this string in text.txt
when i run the program it always print out i have a mousee
Does somebody know what's happening with it? Thanks!
Last edited on
you might want to read up on how get() works from the docs on fstream. It's been overloaded so and each one has its subtleties.

To get it working use this line:

 
 character = fin.get();
1
2
3
4
   while (!fin.eof()) {
      fin.get(character);
      myList.push_back(character);
   }
eof will be set when you read it. The operation fails and character does not change (I think that's undefined), but you put it in the list again.
Change it to
1
2
while( fin.get(character) )
  myList.push_back(character);
Thanks both of you.
Topic archived. No new replies allowed.