ifstream 中的getline的问题

clayXmore 2012-04-24 10:17:41

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
const char *InFile="D:\\InData.txt";

ifstream in(InFile,ifstream::in);
if(!in)
{
cerr<<"Open file "<<InFile<<" failed!"<<endl;
system("pause");
return -1;
}

const int m=11;
char line[m];

while(!in.eof())
{
//in.clear();
in.getline(line,m);
cout<<line<<endl;
}

in.close();
system("pause");
return 0;
}

程序加上in.clear()是对的,但是不加好像程序陷入死循环,而且没有任何的输出,能不能给讲讲这是为什么?
InData.txt的数据是djhgaksdhgkhsfljkglasjdklfjalksdjflsadlkgjlasjdlg;asdsdgalskdfgla
...全文
199 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sjyzhxw 2012-04-26
  • 打赏
  • 举报
回复
坐等高手回答
evencoming 2012-04-25
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]
读的字符的个数小于文件的字符数
[/Quote]
[code=C/C++]
basic_istream<Elem, Tr>& getline(
char_type *_Str,
streamsize _Count
);
basic_istream<Elem, Tr>& getline(
char_type *_Str,
streamsize _Count,
char_type _Delim
);

The first of these unformatted input functions returns getline(_Str, _Count, widen('\n')).

The second function extracts up to _Count - 1 elements and stores them in the array beginning at _Str. It always stores the string termination character after any extracted elements it stores. In order of testing, extraction stops:

At end of file.

After the function extracts an element that compares equal to _Delim, in which case the element is neither put back nor appended to the controlled sequence.

After the function extracts _Count - 1 elements.

If the function extracts no elements or _Count - 1 elements, it calls setstate(failbit). In any case, it returns *this.

_Count
The number of characters to read from strbuf.

_Delim
The character that should terminate the read if it is encountered before _Count.

_Str
A string in which to write.

[/CODE]

再仔细看看. 在你上面的代码中,_Count的值是11.那么仔细看下面这句:
If the function extracts no elements or _Count - 1 elements, it calls setstate(failbit)
clayXmore 2012-04-25
  • 打赏
  • 举报
回复
求高人解答
clayXmore 2012-04-25
  • 打赏
  • 举报
回复
读的字符的个数小于文件的字符数
evencoming 2012-04-24
  • 打赏
  • 举报
回复
看源码吧
或者msdn?
If the function extracts no elements or _Count - 1 elements, it calls setstate(failbit). In any case, it returns *this.

64,439

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧