【问题标题】:Trying to print contents of vector尝试打印矢量的内容
【发布时间】:2013-11-06 18:54:26
【问题描述】:

我一直在努力让 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&lt;string&gt; seqNames;

谢谢, 本。

【问题讨论】:

  • 我建议你使用一些 IDE,这样你甚至可以在编译之前发现这些微不足道的错误。 (我不是反对者)
  • 我使用 Xcode 作为 IDE,虽然只有一个 cpp 文件,由于某种原因在 Xcode 中打开整个项目是不同的 - 仍然习惯使用它。

标签: c++ string vector ifstream


【解决方案1】:

这是因为您在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;
}

【讨论】:

    【解决方案2】:
    if (inputFile.is_open()) {
        vector<string> seqNames;
        vector<string> sequences;
        ...
    }
    for( int i = 0; i < seqNames.size(); i++){
        cout << seqNames[i] << endl;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多