试图打印矢量的内容

时间:2013-11-06 18:54:26

标签: 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;
}

该功能应该通过如下文本文件:

Hello World!
>foo
bleep bleep
>nope

并确定以'&gt;'开头的那些并将它们推送到矢量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;

谢谢, 本。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

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

seqNames语句的范围内定义if。在if语句之后,标识符seqNames未定义。在涵盖iffor的范围内更早地定义它。