Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么一个空行占用两个字节? 我是C++新手。我想计算文本文件末尾的空行。但现在我遇到了一个问题。文本文件的内容如下所示:_C++_Istream_Seekg - Fatal编程技术网

为什么一个空行占用两个字节? 我是C++新手。我想计算文本文件末尾的空行。但现在我遇到了一个问题。文本文件的内容如下所示:

为什么一个空行占用两个字节? 我是C++新手。我想计算文本文件末尾的空行。但现在我遇到了一个问题。文本文件的内容如下所示:,c++,istream,seekg,C++,Istream,Seekg,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

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;
}

在上面显示的结果中,
b
的值也是
\n
。为什么?

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

如果您想执行这些操作,请以二进制模式打开文件。以文本模式打开并使用
seekg
的文件将为您带来惊喜。非常感谢!但是为什么“b”的值也“\n”而不是“\r”?我更喜欢的文件操作是通过stdio.h使用stdout,所以我对iostream不太熟悉,但我想知道seek end-2是否正确,因为如果您已经读取了一个字符,那么如果我回忆起来,那么end将成为缓冲区中的下一个字符。我还要注意一下,如何像Paul建议的那样以文本模式打开文件。fopen(file,'t+')的行为方式让我用fopen(file,'w+')来代替,以避免不必要的复杂性。
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