4

I'm new to C++. I'd like to count the blank lines at the end of a text file. But now i meet a problem. The contents of the text file are like:

test.txt

1
2
blank line

The code is:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream inFile("test.txt",ios::in);
    if (!inFile.good())
    {
        cout << "error" << endl;
    }

    inFile.clear();
    inFile.seekg(-1, ios::end);
    char a;
    inFile.get(a);
    cout << "symbol for a: " << a << "ASCII: " << (int)a << endl;

    inFile.clear();
    inFile.seekg(-2, ios::end);
    char b;
    inFile.get(b);
    cout << "symbol for b: " << b << "ASCII: " << (int)b << endl;
}

The result is:

symbol for a: // a stands for the last character which is '\n'
ASCII: 10
symbol for b: // b stands for the second last character, which should be "2"
ASCII: 10

In the result shown above, the value of b is also \n. Why?

AEM
  • 1,354
  • 8
  • 20
  • 30
Oliver Yu
  • 99
  • 5
  • 6
    Open your file in binary mode if you want to do these `seekg` things. A file opened in text mode and using `seekg` will hold surprises for you. – PaulMcKenzie Apr 12 '20 at 07:37

1 Answers1

4

On Windows, a newline generates two ascii characters "\r\n" (carriage return, line feed) [10,13] Open any source code in a hex editor and youll see the TWO chars at the end of each line.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Stephen Duffy
  • 467
  • 2
  • 14
  • 1
    Thank you so much! But why is the value of 'b' also '\n' instead '\r'? – Oliver Yu Apr 12 '20 at 08:13
  • My preferred file manipulation is via stdio.h using stdout so Im not so familiar with iostream but Im wondering if the seek end - 2 is correct because if youve read a character already then the end becomes the next character in the buffer if I recall. Id also take note about opening files in text mode like Paul suggests. fopen(file,'t+') behaves in fashions that makes me do things fopen(file,'w+') instead to avoid unneccessary complications. – Stephen Duffy Apr 12 '20 at 08:33