我刚开始学习C++。我想要统计文本文件末尾的空白行数。但是我现在遇到了一个问题,文本文件的内容如下:
test.txt
1
2
blank line
代码如下:
#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;
}
结果如下:
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
在上面展示的结果中,
b
的值也是 \n
。为什么?
seekg
进行操作,请以二进制模式打开文件。以文本模式打开并使用seekg
的文件会给你带来意外惊喜。 - PaulMcKenzie