LordNoob LordNoob - 3 months ago 8
C++ Question

why does my code which takes fasta formated DNA and transforms it into a vector crashes on run

I compiled both in code blocks and cygwin but it crashes when i run it.

The source.txt file is formated like this:

>sample1

ACTG

GCA

GTC

>sample2

TAACG

GGCC

And dtb should look something like this:

dtb=(sample1,ACTGGCAGTC,sample2,TAACGGGCC)

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream myfile;
int i=0;
string seq="",holder="";
myfile.open("source.txt");
vector<string> dtb;
while (myfile>> seq)
{
if (seq.substr(0,1)==">")
{
dtb[i]=seq.substr(1,seq.length()-1);
i++;
if (i!=0)
dtb[i]=holder;
holder="";
}
else
{
holder+=seq;
}
}
cout<<dtb[0]<<"\n"<<dtb[1]<<"\n"<<dtb[2]<<"\n"<<dtb[3];
return 0;
}

Answer

A std::vector object starts out empty. That means any indexing in it will be out of bounds and lead to undefined behavior.

You need to add elements to the vector, using e.g. push_back.