2013-05-16 37 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的默认值是以空文件开头。无论文件中已存在什么,都可能导致编辑器使用错误的编码解释数据。