我是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
。为什么?
换行符生成两个ASCII字符“ \ r \ n”(回车,换行)[10,13]在十六进制编辑器中打开任何源代码,您将在每行末尾看到两个字符。