2013-05-16 40 views
3

所以我試圖設計一個程序,輸入一個文件,然後通過行讀取,並採取每一行,並輸出有關它的信息到一個新的文件。Ofstream返回垃圾。 Cout的作品...爲什麼不流入?

我把它全部倒下......除了!我所有的.txt文件都被垃圾填滿,而不是填滿它們。

我找不出來。如果我關注我正在輸入的字符串,右邊的東西會打印在屏幕上。

fstream lineOutFile; 
string newFileName; 
stringstream linefile; 

linefile << lineCt; 
linefile >> newFileName; 

newFileName += ".txt"; 

lineOutFile.open(newFileName.c_str()); 

if(!lineOutFile) 
{ 
    cerr << "Can't open output file.\n"; 
} 

stringstream iss; 
iss << "The corrected 5' x 3' complement of line " << lineCt << 
    " is as follows - \n\n" << finalSeq << "\n\n\n\n" << 
    "This line of DNA sequence is made up of " << cgContent << 
    " C and G neucleotides.\n\n" << "It contains " << polyTCount << 
    " Poly-T strings of more than 4 consecutive neucleotides. They are as follows. - \n" << 
    polyTString << "\n\n There are " << cpgCount << 
    " CpG sites. The locations are as follows - \n" << cpgString; 

string storage; 
storage = iss.str(); 
cout << storage; 
lineOutFile << storage; 
lineOutFile.close(); 
lineCt++; 

} 

我得到 「⁥潣牲捥整⁤✵砠㌠‧」 < <這類瘋狂的在我的.txt文件。

當我立即發出同樣的刺痛時,我會得到正確的結果!

爲什麼我的.txt文件是垃圾?

+0

它是否可以在讀取它們時將您的.txt文件解釋爲Unicode(UTF-16)?然後你會看到垃圾(雖然在8位編碼這看起來是正確的)。 – Inspired

+0

我會怎麼說?它看起來像我的輸入文件是Unicode(UTF-8)。是對的嗎? – stringgy

+0

你正在使用哪種文本編輯器? – Xaqq

回答

0

嘗試運行

LANG=C your_program 

,並關閉編碼識別在編輯器中。更好 - 用cat程序查看你的txt文件。

1

爲什麼使用fstream而不是ofstream

fstream的默認值是打開現有文件。 ofstream的默認值是以空文件開頭。無論文件中已存在什麼,都可能導致編輯器使用錯誤的編碼解釋數據。