Reputation: 99
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?
Upvotes: 4
Views: 597
Reputation: 505
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.
Upvotes: 4