gpt4 book ai didi

c++ - 使用 getline : C++ 读取文件并在屏幕上显示

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:54 25 4
gpt4 key购买 nike

我正在尝试读取包含以下内容的文件:

This is Line One
This is Line Two
This is Line Three
This is Line Four
This is Line Five

代码:

#include <iostream>
#include <fstream>
#include <limits>

using namespace std;

int main()
{

char buff[50];

ifstream is("Test.txt");
if(!is)
cout << "Unable to open Test.txt\n";

while(is.getline(buff,50,'\n'))
{
cout << is.gcount();
cout << buff;
cout << "\n----------------\n";
}
return 0;
}

输出:

$ ./Trial
18This is Line One
----------------
18This is Line Two
----------------
20This is Line Three
----------------
19This is Line Four
----------------
17This is Line Five
----------------

现在假设如果我评论cout << "\n----------------\n";

  while(is.getline(buff,50,'\n'))
{
cout << is.gcount();
cout << buff;
//cout << "\n----------------\n";
}

我得到的输出是:

$ ./Trial
17This is Line Fivee

我无法弄清楚 - 为什么会有这样的行为?

另外,为什么将计数显示为 18(假设第一行 - 第一行包含 16 个字符,包括空格 - 如果我添加 null 它变为 17 - 行尾字符被 getline 丢弃)。

我正在使用 windows-7 和 cygwin。

最佳答案

你说:

I am using windows-7 and cygwin.

问题很可能是你的cygwin环境正在以二进制模式读取文件,但文件是以DOS文本格式保存的。这意味着在发出每一行时,尾随的 \r 字符会导致发出的下一行覆盖前一行。

输出 18 与预期的 16 是因为 \r 加上结尾的 \n

关于c++ - 使用 getline : C++ 读取文件并在屏幕上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com