我一直在为文件解析器函数编写一些代码来学习一些 C++:
它应该在这个文本文件中读取:
>FirstSeq
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
>SecondSeq
TTTTTTTTTTTTTT
>ThirdSequence
CCCCCCCCCCCCCC
>FourthSequence
GGGGGGGGGGGGGG
并打印出名称(开头带有'>'的行),然后是序列。但是从输出中:
AAAAAAAAAAAAAABBBBBBBBBBBBBB
TTTTTTTTTTTTTT
CCCCCCCCCCCCCC
FirstSeq
SecondSeq
ThirdSequence
FourthSequence
我们看到最后一行 G 字符不包括在内。代码如下。它的作用是遍历行,如果找到名称,则将其附加到名称向量中,如果找到序列,则将其附加到临时字符串(以防序列超过一行,如第一个序列),然后当它找到下一个序列的名称时,将构建的临时字符串存储在一个向量中,然后继续覆盖临时字符串并重新开始。我怀疑是因为在函数的while循环中:该行fullSequence.push_back(currentSeq);
每当先前检测到新名称以将旧临时字符串推送到向量时都会调用它,不会为 G 的最后一行调用它,因此它不被包括在内,尽管记录了名称“FourthSeq”,而不是G's 被读入临时字符串,但随后不传递给向量。那么,我怎样才能做到这一点,以便我可以检测到这是文件的最后一行,因此应该确保将临时字符串推送到向量上?
谢谢,本。
代码:
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
void fastaRead(string fileName)
{
ifstream inputFile;
inputFile.open(fileName);
if (inputFile.is_open()) {
vector<string> fullSequence, sequenceNames;
string currentSeq;
string line;
bool newseq = false;
bool firstseq = true;
cout << "Reading Sequence" << endl;
while (getline(inputFile, line))
{
if (line[0] == '>') {
sequenceNames.push_back(line.substr(1,line.size()));
newseq = true;
} else {
if (newseq == true) {
if(firstseq == false){
fullSequence.push_back(currentSeq);
} else {
firstseq = false;
}
currentSeq = line;
newseq = false;
} else {
currentSeq.append(line);
}
}
}
//Report back the sequences and the sequence names...
for ( vector<string>::iterator i = fullSequence.begin(); i != fullSequence.end(); i++) {
cout << *i << endl;
}
for ( vector<string>::iterator i = sequenceNames.begin(); i != sequenceNames.end(); i++) {
cout << *i << endl;
}
cout << fullSequence.size() << endl;
cout << sequenceNames.size() << endl;
inputFile.close();
} else {
perror("error whilst reading this file");
}
if(inputFile.bad()){
perror("error whilst reading this file");
}
}
int main()
{
cout << "Fasta Sequence Filepath" << endl;
string input = "boop.txt";
fastaRead(input);
return 0;
}