Chinaunix

标题: 请教一个关于文件输入流的问题 [打印本页]

作者: zjw0722    时间: 2014-03-21 07:43
标题: 请教一个关于文件输入流的问题
代码文件strfile.cpp:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <assert.h>

  4. using namespace std;
  5. const int SZ = 100;
  6. int main()
  7. {
  8.         char buf[SZ];
  9.         {
  10.                 ifstream in("strfile.cpp");
  11.                 assert(in);
  12.                 ofstream out("strfile.out");
  13.                 assert(out);
  14.                 int i = 1;
  15.                
  16.                 while(in.get(buf, SZ))
  17.                 {
  18.                         in.get(); // throw away next character
  19.                         cout << buf << endl;
  20.                         out << i++ << ": " << buf << endl;
  21.                 }
  22.         }
  23.         ifstream in("strfile.out");
  24.         assert(in);
  25.         while(in.getline(buf, SZ))
  26.         {
  27.                 char *cp = buf;
  28.                 while(*cp != ':')
  29.                 {
  30.                         cp++;
  31.                 }
  32.                 cp += 2;
  33.                 cout << cp << endl; // must still add \n
  34.         }
  35. }
复制代码
我的问题是,输入流的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.
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <cassert>
  5. using namespace std;

  6. int main()
  7. {
  8.     {
  9.         ifstream in("strfile.cpp");
  10.         assert(in);
  11.         ofstream out("strfile.out");
  12.         assert(out);

  13.         size_t lineno = 1;
  14.         for( string line; getline(in,line); ++lineno )
  15.         {
  16.             cout << line << endl;
  17.             out << lineno << ": " << line << '\n';
  18.         }
  19.     }

  20.     ifstream in("strfile.out");
  21.     assert(in);
  22.     for( string line; getline(in,line); )
  23.     {
  24.         size_t pos = line.find(':');
  25.         cout << line.c_str()+pos+2 << endl;
  26.     }

  27.     return 0;
  28. }
复制代码

作者: 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