Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is a C++ question. This function is supposed to read only the last line of

ID: 3765196 • Letter: T

Question

This is a C++ question. This function is supposed to read only the last line of the text file. Any help would be appreciated.

Here is what is in the text file: (the file is named punchline.txt)

asfasdfasdfasdfsdf

asdfasdfsadfsadfsadf

asdfsadfsdfsdf

"I can't work in the dark," he said.

I can not seem to get this to work. The function should display only the last line of the file it is passed.

IT should find this line by seeking to the end of the file and then backing up to the beginning of the last line.

void displayLastLine(ifstream &infile)
{
   cout << " Punchline: ";
   string line;
   infile.seekg(0L, ios::end);
   if (infile)
   {
       getline(infile, line);
       while (line < 1)
       {
           long pos = infile.tellg();
           seekTo--;
       }
       infile >> line;
       cout << " " << line << endl;
   }
}

Explanation / Answer

#include<iostream>
#include<string>

using namespace std;

void displayLastLine(ifstream &infile)
{
   infile.open("Myfile");
   cout << " Punchline: ";
   string line;

   if (infile)
   {
       while(!infile.eof())
        {     
            getline(infile, line);
            infile >> line;
  
       }
       cout << " " << line << endl;
   }
}

void main()
{
   ifstream f;

   displayLastLine(f);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote