Chinaunix
标题:
请教一个关于文件输入流的问题
[打印本页]
作者:
zjw0722
时间:
2014-03-21 07:43
标题:
请教一个关于文件输入流的问题
代码文件strfile.cpp:
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;
const int SZ = 100;
int main()
{
char buf[SZ];
{
ifstream in("strfile.cpp");
assert(in);
ofstream out("strfile.out");
assert(out);
int i = 1;
while(in.get(buf, SZ))
{
in.get(); // throw away next character
cout << buf << endl;
out << i++ << ": " << buf << endl;
}
}
ifstream in("strfile.out");
assert(in);
while(in.getline(buf, SZ))
{
char *cp = buf;
while(*cp != ':')
{
cp++;
}
cp += 2;
cout << cp << endl; // must still add \n
}
}
复制代码
我的问题是,输入流的get()方法不是应该在遇到文件结尾标识符时返回假么,也就是从while循环中退出么?但是我的问题时,此程序当读取到空行时就会从while循环退出了,小弟新手,请大家帮一下吧,谢谢了。
作者:
bruceteen
时间:
2014-03-21 08:37
你这代码很奇葩。
对于你的问题,If the function extracts no elements, it calls setstate(failbit). In any case, it returns *this.
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
int main()
{
{
ifstream in("strfile.cpp");
assert(in);
ofstream out("strfile.out");
assert(out);
size_t lineno = 1;
for( string line; getline(in,line); ++lineno )
{
cout << line << endl;
out << lineno << ": " << line << '\n';
}
}
ifstream in("strfile.out");
assert(in);
for( string line; getline(in,line); )
{
size_t pos = line.find(':');
cout << line.c_str()+pos+2 << endl;
}
return 0;
}
复制代码
作者:
zjw0722
时间:
2014-03-21 11:19
回复
2#
bruceteen
怎么,这是think in C++里的例子啊,你说的我没明白,能说清楚点么?
作者:
bruceteen
时间:
2014-03-21 12:19
回复
3#
zjw0722
没看过《think in C++》,但上帝拉的屎也是臭的。
但你用别人的代码,那符合不符合别人的契约?从那代码看,文件每行必须小于100个字符,且不允许有空行。
而你的需要竟然允许有空行,那怎么可以用别人的代码?
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2