[英]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.