War*_*250 2 c++ string vector ifstream
我一直在努力使用C++变得越来越舒服,我开始尝试编写一些文件操作的东西.我正在解决能够解析fasta文件的问题,我遇到了一些问题:
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//A function for reading in DNA files in FASTA format.
void fastaRead(string file)
{
ifstream inputFile;
inputFile.open(file);
if (inputFile.is_open()) {
vector<string> seqNames;
vector<string> sequences;
string currentSeq;
string line;
while (getline(inputFile, line))
{
if (line[0] == '>') {
seqNames.push_back(line);
}
}
}
for( int i = 0; i < seqNames.size(); i++){
cout << seqNames[i] << endl;
}
inputFile.close();
}
int main()
{
string fileName;
cout << "Enter the filename and path of the fasta file" << endl;
getline(cin, fileName);
cout << "The file name specified was: " << fileName << endl;
fastaRead(fileName);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该函数应该通过如下文本文件:
Hello World!
>foo
bleep bleep
>nope
Run Code Online (Sandbox Code Playgroud)
并确定以'>'开头的那些并将它们推送到矢量seqNames,然后将内容报告回命令行. - 所以我正在尝试编写检测快速格式磁头的功能.但是当我编译时,我被告知:
n95753:Desktop wardb$ g++ testfasta.cpp
testfasta.cpp:25:25: error: use of undeclared identifier 'seqNames'
for( int i = 0; i < seqNames.size(); i++){
^
testfasta.cpp:26:17: error: use of undeclared identifier 'seqNames'
cout << seqNames[i] << endl;
Run Code Online (Sandbox Code Playgroud)
但是我很确定我在行中声明了向量:
vector<string> seqNames;
谢谢,本.
这是因为你在内部范围内声明了向量if.您需要移出声明,以便您的while循环也可以看到它们:
vector<string> seqNames;
vector<string> sequences;
if (inputFile.is_open()) {
string currentSeq;
string line;
while (getline(inputFile, line))
{
if (line[0] == '>') {
seqNames.push_back(line);
}
}
}
for( int i = 0; i < seqNames.size(); i++){
cout << seqNames[i] << endl;
}
Run Code Online (Sandbox Code Playgroud)