I've been trying to get more and more comfortable with C++ and I've moved to trying to write some file manip stuff. I was halfway through something that would be able to parse fasta files and I got a little stuck:

#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;
}

The function should go through a text file like the one below:

Hello World!
>foo
bleep bleep
>nope

and identify the ones beginning with '>' and push them onto the vector seqNames and then report back the contents to the command line. - So I'm trying to write the ability to detect fast format heads. However when I compile I am told:

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;

However I'm pretty sure I declared the vector in the line: vector<string> seqNames;

Thanks, Ben.

有帮助吗?

解决方案

This is because you declared the vectors in the inner scope of the if. You need to move the declaration out, so that your while loop can see them as well:

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;
}

其他提示

if (inputFile.is_open()) {
    vector<string> seqNames;
    vector<string> sequences;
    ...
}
for( int i = 0; i < seqNames.size(); i++){
    cout << seqNames[i] << endl;
}

defines seqNames in a scope of if statement. After the if statement, the identifier seqNames is undefined. Define it earlier in a scope that covers both if and for.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top