Question

In: Computer Science

For the punchline file, we are going to display the last sentence. You could try to...

  1. For the punchline file, we are going to display the last sentence. You could try to use a while loop which executes while the "file" is true and use break statement to terminate the loop when '\n' is encountered ('\n' here is the one right before the last line). This could also be done using bool and a false assignment. Just keep checking the character at this byte for the new line indicator as you step backward and you should end at the correct location. Keep in mind that when you use seekg, you will go forward one step in the txt file each time if you use file.get to read the character at this location.

    ope the template will help here. Assume you already open the punchline file as 'infile'.

       char ch;                    // To hold a character
       string line;                   // To hold a line of input
       bool foundLastLine = false; // Flag, intitalized to false
           
       // Find the beginning of the last line
       // Clear the eof bit just in case we're
       // already at end of the file.
       infile.clear();

       // Go to the end of the file.
       infile.seekg(0, ios::end);
       
       // Move backwards to beginning of the
       // final char in the file and read it in
       infile.seekg(-1, ios::cur);
       ch = infile.get();
      
       // Back up until we find a newline.
       while (infile && !foundLastLine)
       {
          // If the char just read is NOT a newline...
          if.....
          {
             // Back up two more characters (one
             // to skip the char just read and one
             // more to move just before the previous
             // char so we can read it next.
           .............

           .............


          }
          else
          {
             // We found the newline at the end of the
             // next to last line, so we are where we
             // want to be. The next char begins the
             // final line.
             foundLastLine = true;
          }
       }
       
       // Read final line and display it
       getline(infile, line, '\n');
       cout << line;

  2. Besides above method, there is another way you can use. You can keep reading lines until the end of the file. The last line just read is the one to print it out.  

C++

Solutions

Expert Solution

I used ifstream headerfile to read the file which supports seekg() function.

seekg() is used to move the location by some characters from the stated position.

if we used infile.seekg(0,ios::end) then it will 1st move the end of the file and from there it will move 0 characters from eof it's stays in the same position.

if we use seekg(10,std::beg) -> then it will 1st go the start of the file and from there it will move 10 characters in forward direction.

here offset is positive then moves forward, if negative moves backward.

So, we will move some -i characters backward for each character reading.

Since we read the last character in infile.seekg(-1,ios::end) we will move the location to 2nd position from end i.e -2 after reading second file we will read 3rd character by moving 3 locations backward i.e -3 like this we will keep on increasing i value and move backwards by 1 character.

What if there is only 1 line in the file?

Here we won't get '\n' character in file how it terminates then. For that we will get the size of the file and we will check whether the value of i is greater than the size of the file or not. If i is greater then we will move to the beginning of file and breaks the loop.

Code:

#include<bits/stdc++.h>
using namespace std;
int main(){
   ifstream infile("C:\\Users\\S\\Desktop\\data.txt",std::ios::ate);
   char ch; // To hold a character
   string line; // To hold a line of input
   bool foundLastLine = false;
   infile.clear();
  
   // Go to the end of the file.
   infile.seekg(0, ios::end);
     
   // Move backwards to beginning of the
   // final char in the file and read it in
   infile.seekg(-1, ios::cur);
   ch = infile.get();
   // Back up until we find a newline.
   std::streampos size = infile.tellg();
//cout<<size;
   int i=2;
   while (infile && !foundLastLine)
   {
   // If the char just read is NOT a newline...
   if(ch!='\n')
   {
       if(i>size){
           infile.seekg(0,ios::beg);
               break;
           }
       infile.seekg(-i,std::ios::end);
       ch=infile.get();
           //cout<<ch;
           ++i;
   }
   else
   {
   foundLastLine = true;
   }
   }
     
   // Read final line and display it
   getline(infile, line, '\n');
   cout << line;
}

Sample Run:

input file:

In addition to good(), which checks whether the stream is ready for input/output operations

Output:

In addition to good(), which checks whether the stream is ready for input/output operations

input file:

Using this prototype, the position of the get or put pointer is set to an offset value relative to some
specific point determined by the parameter direction. offset is of the member
type off_type, which is also an integer type. And direction is of type seekdir, which is an enumerated type (enum) that determines
the point from where offset is counted from, and that can take any of the following values

Output:

the point from where offset is counted from, and that can take any of the following values


Related Solutions

Write a java program that read a line of input as a sentence and display: ...
Write a java program that read a line of input as a sentence and display:  Only the uppercase letters in the sentence.  The sentence, with all lowercase vowels (i.e. “a”, “e”, “i”, “o”, and “u”) replaced by a strike symbol “*”.
You are going to carry out a gastric lavage (stomach pump) in order to try and...
You are going to carry out a gastric lavage (stomach pump) in order to try and get rid of the aspirin that has not yet been absorbed. The procedure involves washing the organ with a solution of a certain pH containing activated charcoal to bind the aspirin. The pH of the stomach is typically around 2.0. Which of the following do you think would be the most effective lavage? Hint: think about the pH at which aspirin would cross the...
The input file Each line of the input file will contain a sentence with words separated...
The input file Each line of the input file will contain a sentence with words separated by one space. Read a line from the listed below  and use a StringTokenizer to extract the words from the line. The input file . Mary had a little lamb whose fl33ce was white as sn0w And everywhere that @Mary went the 1amb was sure to go. Read the above that contains a paragraph of words. Put all the words in an array, put the...
solution using stack Reversing a word or a sentence: Write an algorithm that will display a...
solution using stack Reversing a word or a sentence: Write an algorithm that will display a given word in a reverse order. - e.g. "Data Structures" will be "serutcurtS ataD".
Display the shortest words in a sentence in JAVA Write a method that displays all the...
Display the shortest words in a sentence in JAVA Write a method that displays all the shortest words in a given sentence. You are not allowed to use array In the main method, ask the user to enter a sentence and call the method above to display all the shortest words in a given sentence. You must design the algorithms for both the programmer-defined method and the main method.
In this question you are going to calculate the data that could be used to construct...
In this question you are going to calculate the data that could be used to construct a titration curve (pH versus volume of titrant added) for the titration of an aqueous ammonia (NH3; weak base, pKB = 4.7) cleaning solution with a strong acid (HCl). When strong acid is added to an aqueous solution, it immediately reacts and yields H3O + ions; thus the titration is described by the reaction: NH3(aq) + H3O + (aq)  NH4 + + H2O(l)...
explain the going concern principal in no more that 2-3 sentence .
explain the going concern principal in no more that 2-3 sentence .
Based on this player.h file, could you make a player.c file which defines the 4 functions?...
Based on this player.h file, could you make a player.c file which defines the 4 functions? Thanks. player.h: #ifndef PLAYERH #define PLAYERH #define MAX_ITEMS 10 typedef struct Player { int location; int num_items; int mitems[MAX_ITEMS] }t_player; void player_init_player(t_player *player, int location); //initialize player void player_add_item(t_player *player, int item); void player_remove_item(t_player *player, int item); int player_has_item(t_player *player, int item); //returns -1 if no item exists #endif
On the last page of this file you will find the Excel output for a multiple...
On the last page of this file you will find the Excel output for a multiple linear regression model. The model was built in an attempt to better understand why students at area high schools perform differently on the state high school mathematics test. The average test score for a class of students is what we are trying to predict. In our attempt to understand why these test scores differ, we use 3 independent variables: a rating (0-100) for the...
Try to get in touch with any person you know( it could be your relative or...
Try to get in touch with any person you know( it could be your relative or friend) who undergone or undergoing a special diet. Describe what it is made of and for what specific condition it is. You may cite specific food items and other details pertinent to the diet.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT