我试图读取文件以下内容:读取文件,并使用函数getline显示在屏幕上:C++
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。
在我看来,该行获取与每次循环覆盖。如果你不是'cout <<“\ n ---------------- \ n”;'写'cout << endl;'?你也不应该''使用命名空间标准;' – olevegard 2013-05-13 06:18:47
我猜这个问题是在cygwin环境中。你可以尝试将输出重定向到文件'$。/ Trial> out.txt'吗? – nullpotent 2013-05-13 06:22:32