2

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

関数は、次のようなテキスト ファイルを通過する必要があります。

Hello World!
>foo
bleep bleep
>nope

「>」で始まるものを特定し、それらをベクトル 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;

ただし、次の行でベクトルを宣言したと確信しています。 vector<string> seqNames;

ありがとう、ベン。

4

2 に答える 2

5

これは、 の内部スコープでベクトルを宣言したためです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;
}
于 2013-11-06T18:55:57.333 に答える