[英]Detect last line of file C++
我一直在研究一些文件解析器函数的代码来学习一些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被读入临时字符串,但不会传递给向量。 那么,我怎么能这样做,因为我可以检测到这是文件的最后一行,所以应该确保临时字符串被推送到向量?
谢谢,本。
码:
#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;
}
当Getline()在行中找到EOF时会“失败”,因此您读取的最后一行不会通过循环。
我已经通过两种方式解决了这个问题,或者通过处理两个标志,或者只是通过处理循环后的最后一行。
对于两个标志,循环要求两者都为真,在getline()失败时将其设置为false,如果第一个为假,则将另一个设置为false,这将在EOF之后为您提供一个额外的循环。
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.