title: reading until the end of file in C++
body: <p>I'm trying to read till the end of a file for a phonebook app that im converting from C to C++. When I print the the results from the file i get this:</p>
  
  <pre><code>johnny smith
  (Home)3
  (Cell)4
  x☺&gt; x☺&gt;
  (Home)4
  (Cell)4
  </code></pre>
  
  <p>it should print:</p>
  
  <pre><code>johnny smith
  (Home)3
  (Cell)4
  </code></pre>
  
  <p>Right now I'm using <code>while(!infile.eof())</code> which i've read is a poor practice, but when I use <code>infile.getline()</code> I get a repeat of the first and last name, and the format is all jacked up. Is there anyway(or another way) to get rid of the junk at the end of the input or another way to read till the end of file in C++ that fixes this. I've been reading about different solutions, but the one a lot of sites seem to agree on is <code>fgets</code>, which is what I had with the original C version, but obviously <code>fgets</code> doesn't work with <code>ifstream</code> which is what I'm using. here is the code:</p>
  
  <pre><code>void contacts:: readfile(contacts*friends ,int* counter, int i,char buffer[],char    user_entry3[])
  {
     ifstream read;
     read.open(user_entry3,ios::in);
     int len;
     contacts temp;
     *counter=0;
     i=0; 
  
       while (!read.eof()) { 
         temp.First_Name=(char*)malloc(36); 
         temp.Last_Name=(char*)malloc(36); 
  
         read&gt;&gt;temp.First_Name&gt;&gt;temp.Last_Name;
  
         read&gt;&gt;buffer;
         len=strlen(buffer);
         if(buffer[len-1]=='\n')
            buffer[len-1]='\0';
  
         temp.home=(char*)malloc(20); 
         strcpy(temp.home, buffer);
  
         read&gt;&gt;buffer;
         len=strlen(buffer);
         if(buffer[len-1]=='\n')
         buffer[len-1]='\0';
  
  
         temp.cell=(char*)malloc(20); 
         strcpy(temp.cell, buffer); 
  
        friends[i].First_Name=(char*)malloc(MAXNAME);
        friends[i].Last_Name=(char*)malloc(MAXNAME);
        friends[i].home=(char*)malloc(MAXPHONE);
        friends[i].cell=(char*)malloc(MAXPHONE);
  
  
    //adds file content to the structure
        strcpy(friends[*counter].First_Name,temp.First_Name);
        strcpy(friends[*counter].Last_Name,temp.Last_Name);
        strcpy(friends[*counter].home,temp.home);
        strcpy(friends[*counter].cell,temp.cell);
  
  
       (*counter)++;
       i++; 
  
     }
     //closes file and frees memory
      read.close();
      free(temp.Last_Name);
      free(temp.First_Name);
      free(temp.home);
      free(temp.cell);
  }
  </code></pre>