2012-07-12 27 views
2

代碼strfile.cpp:fstream get(char *,int)如何操作空行?

#include <fstream> 
#include <iostream> 
#include <assert.h> 

#define SZ 100 

using namespace std; 

int main(){ 
char buf[SZ]; 
{ 
    ifstream in("strfile.cpp"); 
    assert(in); 
    ofstream out("strfile.out"); 
    assert(out); 
    int i = 1; 

    while(!in.eof()){ 
     if(in.get(buf, SZ)) 
      int a = in.get(); 
     else{ 
      cout << buf << endl; 
      out << i++ << ": " << buf << endl; 
      continue; 
     } 
     cout << buf << endl; 
     out << i++ << ": " << buf << endl; 
    } 
} 
return 0; 
} 

我想工作的所有文件 但strfile.out:

1: #include <fstream> 
2: #include <iostream> 
3: #include <assert.h> 
4: ...(many empty line) 

我知道fstream.getline(字符*,INT)該功能可管理它,但我想知道如何做到這一點只是使用函數「fstream.get()」。

+0

你是什麼意思「如何操作」嗎?你想忽略空行嗎?你的代碼在空行上失敗了嗎? – user7116 2012-07-12 14:05:43

+0

對不起我的英語不好。我什麼是當有一個空行,輸出行號。 – lanmezhe 2012-07-12 14:17:01

+0

如果您想要複製文件並在每行或100個字符後插入一個行號(以先發生者爲準),它對我來說工作正常。你能對你的問題更具體嗎? – molbdnilo 2012-07-12 14:26:25

回答

1

因爲ifstream::get(char*,streamsize)將離開分隔符(在這種情況下\n)在流,你的電話永遠不會進步,因此它似乎你正在閱讀不休空行的調用程序。

相反,你需要確定一個換行符在流等,並移動過去,它使用in.get()in.ignore(1)

ifstream in("strfile.cpp"); 
ofstream out("strfile.out"); 

int i = 1; 
out << i << ": "; 

while (in.good()) { 
    if (in.peek() == '\n') { 
     // in.get(buf, SZ) won't read newlines 
     in.get(); 
     out << endl << i++ << ": "; 
    } else { 
     in.get(buf, SZ); 
     out << buf;  // we only output the buffer contents, no newline 
    } 
} 

// output the hanging \n 
out << endl; 

in.close(); 
out.close(); 
+0

謝謝,我知道getline()可以做到。我只想知道如何做到這一點只使用get()。 – lanmezhe 2012-07-12 14:19:59

+0

@lanmezhe:好的,現在我明白了。我已更新我的示例。 – user7116 2012-07-12 14:49:10

+0

謝謝你,它的作品!我認爲問題是,當get(buf,SZ)讀取空行時,程序出錯了。是對的嗎? – lanmezhe 2012-07-12 15:28:25