1

I'm trying to read the last thing from a text file I've created.

Currently the file contains for e.g "5 + 3 - 2". I'm trying to write a function for when the user presses the m key on the keyboard, it displays the last thing in the file, which in this scenario would be 2.

It sounds simple but I just can't get it to work properly. Currently I have this code. Can anyone help me out? For further clarity, I want the 2 to be displayed.

void DisplayLast(string input) { // FUNCTION FOR IF USER PRESSES M

string temp;

    ifstream fileInp("About.txt", ios::in);
    if(!fileInp) {
        cout << "Failed to open" << endl;
    }

    while(!fileInp.eof()) {
        getline(fileInp, temp);
    }

    cout << "Last: " << temp << endl;
}

With this code above, it doesn't display anything. I'm assuming that this is because I'm at the end of the file which has NULL.

jkinlol1
  • 19
  • 2
  • Check this post: http://stackoverflow.com/questions/7868936/read-file-line-by-line – JSON C11 Apr 07 '15 at 02:44
  • Why don't you save whatever you read from the file in a different variable, and then print it later? – CinCout Apr 07 '15 at 02:56
  • @Stallion I've approved your suggested edit but please try to make them more substantial in the future. Please see [my revision](http://stackoverflow.com/posts/29482808/revisions) for an example of all of the things that you could have addressed besides adding a single tag. – Radiodef Apr 07 '15 at 03:16
  • @Radiodef Hey thanks for the feedback. I will look at the whole question in more detail next time. It never occurred to me that I should correct typos and grammatical errors. – JSON C11 Apr 07 '15 at 03:24
  • Thanks for the reply ! I edited the original post as to putting whatever I read from the file in a different variable. In regards to the post you linked me to, it didn't help. Simply put, how can I write a function to return the last input at the end of a file ? – jkinlol1 Apr 07 '15 at 03:46
  • You might read through this: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong `while(getline(...))` is a better choice. – Retired Ninja Apr 07 '15 at 03:47
  • Thank you, I found a solution. – jkinlol1 Apr 07 '15 at 05:33

0 Answers0