Question

I'm practicing C++ and have made a class that stores sequences read in from fast format as well as their names. The code is below:

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

However when I run the program with the following dummy input file:

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

I get a segmentation fault when the line inset.getSequence(0) is called. What is it I've done that causes the seg fault and how do I make sure it doesn't happen? I know it can have something to do with errors in pointers, but I don't think I've used pointers which if I remember correctly requires the * character.

Thanks, Ben.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top