0

我正在尝试打开一个 ifstream,然后使用输入文件中的信息,对其进行操作并将结果保存到每行的新 .txt 文件中。

当我计算它时,我得到了正确的东西,但是我的 .txt 文件中的垃圾。

这不合法吗?我必须遵守捉鬼敢死队规则而不是越过溪流吗?我认为它有效,因为它们是不同的流,但也许我错了?我搜索并找不到这个问题的答案。

有没有更好的方法来做到这一点,我没有考虑过?

是的,这是硬件。感谢您对我的任何帮助!

ifstream userFile;              // Open the input file
string line;    
userFile.open(filename.c_str());

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

while (getline(userFile, line))
    {

    istringstream ss(line);

    //...... (DO STUFF TO THE LINE HERE)


                    // Here we are creating the file to write to.

    ofstream lineOutFile;

    string newFileName;

    stringstream linefile;
    linefile << lineCt;
    linefile >> newFileName;

    newFileName += ".txt";

    lineOutFile.open(newFileName.c_str(), ios::out);

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

lineOutFile << "            •Original line of sequence - " << origLine;

lineOutFile << "\n\nThe corrected 5' x 3' complement of line " << lineCt << " is as follows - \n\n" << finalSeq << "\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.\n";

if(polyTCount > 0)
    lineOutFile << "They are as follows. - \n" <<  polyTString;

lineOutFile << "\nThere are " << cpgCount << " CpG sites.";

if(cpgCount > 0)
    lineOutFile << "The locations are as follows - \n" << cpgString;

    lineOutFile.close();    

    lineCt++;

    }

userFile.close();

}

这些文件确实可以正确打开(1.txt 2.txt 3.txt...等),但其中有垃圾。

4

1 回答 1

1

是的,至少允许、支持并与我使用的每个 C++ 编译器一起工作的基本想法。

快速演示:

int main(){ 
    std::istringstream in("one\ntwo\nthree");

    std::string line;

    for (int i = 1; in >> line; i++) {
        std::ofstream out(lexical_cast<std::string>(i) + ".txt");
        out << line;
    }
    return 0;
}

结果:

1.txt:
one

2.txt:
two

3.txt:
three
于 2013-05-15T22:28:40.087 回答