亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標(biāo)題: 請教一個關(guān)于文件輸入流的問題 [打印本頁]

作者: zjw0722    時間: 2014-03-21 07:43
標(biāo)題: 請教一個關(guān)于文件輸入流的問題
代碼文件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. }
復(fù)制代碼
我的問題是,輸入流的get()方法不是應(yīng)該在遇到文件結(jié)尾標(biāo)識符時返回假么,也就是從while循環(huán)中退出么?但是我的問題時,此程序當(dāng)讀取到空行時就會從while循環(huán)退出了,小弟新手,請大家?guī)鸵幌掳,謝謝了。
作者: 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. }
復(fù)制代碼

作者: zjw0722    時間: 2014-03-21 11:19
回復(fù) 2# bruceteen
怎么,這是think in C++里的例子啊,你說的我沒明白,能說清楚點(diǎn)么?


   
作者: bruceteen    時間: 2014-03-21 12:19
回復(fù) 3# zjw0722

沒看過《think in C++》,但上帝拉的屎也是臭的。
但你用別人的代碼,那符合不符合別人的契約?從那代碼看,文件每行必須小于100個字符,且不允許有空行。
而你的需要竟然允許有空行,那怎么可以用別人的代碼?




歡迎光臨 Chinaunix (http://www.72891.cn/) Powered by Discuz! X3.2