我正在练习C ++,并完成了一堂课,该课程存储了从快速格式及其名称中读取的序列。代码如下:

#include<fstream>
#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Sequence {
    vector<string> fullSequence, sequenceNames;

public:
    void fastaRead(string fileName);
    string getSequence(int index);

};

string Sequence::getSequence(int index)
{
    return fullSequence[index];
}


void Sequence::fastaRead(string fileName)
{
    vector<string> fullSequence, sequenceNames;
    ifstream inputFile;
    inputFile.open(fileName);
    if (inputFile.is_open()) {
        string currentSeq;
        string line;
        bool newseq = false;
        while (getline(inputFile, line))
        {
            if (line[0] == '>') {
                sequenceNames.push_back(line.substr(1,line.size()));
                newseq = true;
            } else {
                if (newseq == true) {
                    fullSequence.push_back(currentSeq);
                    currentSeq = line;
                    newseq = false;
                } else {
                    currentSeq.append(line);
                }
            }
        }
    }
    inputFile.close();
}


int main()
{
    Sequence inseq;
    cout << "Fasta Sequence Filepath" << endl;
    string input;
    getline(cin, input);
    inseq.fastaRead(input);
    inseq.getSequence(0);
    return 0;
}

但是,当我使用以下虚拟输入文件运行程序时:

>FirstSeq
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
>SecondSeq
TTTTTTTTTTTTTT
>ThirdSequence
CCCCCCCCCCCCCC
>FourthSequence
GGGGGGGGGGGGGG

当行时,我会得到一个细分错误 inset.getSequence(0) 叫做。我做了什么会导致SEG故障,如何确保它不会发生?我知道这可能与指针中的错误有关,但是我认为我没有使用指针,如果我记得正确地需要 *角色。

谢谢,本。

有帮助吗?

解决方案

You need to remove vector<string> fullSequence, sequenceNames; in the void Sequence::fastaRead function. When you define those variables inside that function and use them, you are not accessing the ones in the class that have the same name, you are accessing the local variables that you have defined in that function, unless you prepend them with this-> while accessing.

The variables in the class are actually empty and you get a segmentation fault.

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