2014-10-08 64 views
0

我編寫了一個快速的C++程序,要求用戶輸入文本文件和輸出文本文件。然後該程序應該爲左邊空白處的文件中的行編號。然而,我似乎無法正常工作,它編譯得很好,但不會像它應該的那樣編號。我相信這是我的一個邏輯錯誤。我對C++中的I/O文件也不太熟悉,因爲我現在只是使用舊式教科書來學習它。使用C++編寫文件中的行

以下是文件:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cassert> 
#include <cstdio> 

using namespace std; 

int main(void) 
{int i = 0 , num = 1; 
string inputFileName; 
string outputFileName; 
string s; 
ifstream fileIn; 
ofstream fileOut; 
char ch; 

cout<<"Enter name of input file: "; 
cin>>inputFileName; 
cout<<"Enter name of output file: "; 
cin>>outputFileName; 

fileIn.open(inputFileName.data()); 
fileOut.open(outputFileName.data()); 

assert(fileIn.is_open()); 
assert(fileOut.is_open()); 

while (!(fileIn.eof())) 
     {ch=fileIn.get(); 
     if (ch=='\n') num++; 
      fileOut << num << "\n"; 
     s.insert(i,1,ch);  //insert character at position i 
     i++; 
     } 
fileOut << s; 
fileIn.close(); 
fileOut.close(); 
return 0; 
} 

如果任何人都可以點我在THR正確的方向,或給我一些建議,我將永遠感激。

+0

不要聲明在非調試環境下合法失敗的東西,比如文件沒有打開。在while循環中檢查eof是錯誤的。 – 2014-10-08 01:08:53

+0

你能向我解釋爲什麼它是錯誤的或提供一個鏈接,以便我可以學習? – NinjaZ 2014-10-08 01:10:44

+0

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – 2014-10-08 01:11:16

回答

4
int i = 0; 
string line; 
while (getline(infile, line)) 
{ 
    outfile << (i++) << " " << line << "\n"; 
} 
+0

好吧,所以我應該修改我的while循環到這樣的東西? – NinjaZ 2014-10-08 01:11:51

+0

是的,這是我將如何實現它。比一次獲取角色要容易得多。 – 2014-10-08 01:12:20

+0

@RemyLebeau你爲什麼編輯我的答案讓它變得更糟?文件流中的endl使其變慢。 – 2014-10-08 01:16:44