4

我是 C++ 新手。我想计算文本文件末尾的空白行。但现在我遇到了一个问题。文本文件的内容如下:

测试.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。为什么?

4

1 回答 1

4

在 Windows 上,换行符会生成两个 ascii 字符“\r\n”(回车,换行)[10,13] 在十六进制编辑器中打开任何源代码,您会在每行末尾看到两个字符。

于 2020-04-12T07:46:00.467 回答