回流垃圾。库特作品...为什么不流?

Ofstream returning garbage. Cout works... Why doesn't ofstream?

本文关键字:为什么不      更新时间:2023-10-16

因此,我正在尝试设计一个程序,该程序输入一个文件,然后读取行,获取每一行并将有关它的信息输出到一个新文件。

我把它都记下来了。。。除了我所有的.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 - nn" << finalSeq << "nnnn" <<
    "This line of DNA sequence is made up of " << cgContent <<
    " C and G neucleotides.nn" << "It contains " << polyTCount <<
    " Poly-T strings of more than 4 consecutive neucleotides. They are as follows. - n" <<
    polyTString << "nn 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文件是垃圾?

为什么使用fstream而不是ofstream

fstream的默认设置是打开现有文件。ofstream的默认设置是从一个空文件开始。文件中已经存在的内容可能会导致编辑器使用错误的编码来解释数据。

尝试运行

LANG=C your_program

并在编辑器中关闭编码识别。更好的是,使用cat程序查看您的txt文件。