Thursday 23 June 2016

c++ - vector in function - how to do return



I've got a function that should read from file line by line, the reading stops when a line does not begin with '>' or ' '. It should store the lines in vector and return it.
This is code:



    #include 

#include
#include
#include
#include
#include

using namespace std;

string getseq(char * db_file) // gets sequences from file
{

string seqdb;
vector seqs;
ifstream ifs(db_file);
string line;

//vector seqs[size/3];

while(ifs.good())
{
getline(ifs, seqdb);

if (seqdb[0] != '>' & seqdb[0]!=' ')
{
seqs.push_back(seqdb);
}
}

ifs.close();
//return seqs;

//return seqs;

}

int main(int argc, char * argv[1])
{
cout << "Sequences: \n" << getseq(argv[1]) << endl;
return 0;
}


Compiler (g++) returns:




    fasta_parser.cpp: In function ‘std::string getseq(char*)’:
fasta_parser.cpp:32: error: conversion from ‘std::vector, std::allocator >, std::allocator, std::allocator > > >’ to non-scalar type ‘std::string’ requested`


Anyone has any idea?



Edit:
As Skurmendel ask, I am adding whole code because of memory security violation after




executing compiled code:



#include 
#include
#include
#include
#include
#include

using namespace std;


vector getseq(char * db_file) // pobiera sekwencje z pliku
{
string seqdb;
vector seqs;
ifstream ifs(db_file);
string line;

//vector seqs[size/3];


while(ifs.good())
{
getline(ifs, seqdb);
if (seqdb[0] != '>' & seqdb[0]!=' ')
{
seqs.push_back(seqdb);
}
}

ifs.close();

return seqs;
}

int main(int argc, char * argv[1])
{
vector seqs; // Holds our strings.
getseq(argv[1]); // We don't return anything.

// This is just a matter of taste, we create an alias for the vector iterator type.
typedef vector::iterator string_iter;


// Print prelude.
cout << "Sekwencje: \n";

// Loop till we hit the end of the vector.
for (string_iter i = seqs.begin(); i != seqs.end(); i++)
{
cout << *i << " "; // Do processing, add endlines, commas here etc.
}


cout << endl;
}

Answer



If I understood you, your getseq() should return a vector of strings. Therefore you should change



string getseq(char * db_file)


to




vector getseq(char * db_file)


And if you want to print it on main() you should do it in a loop.



int main() {
vector str_vec = getseq(argv[1]);
for(vector::iterator it = str_vec.begin(); it != str_vec.end(); it++) {
cout << *it << endl;

}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...