Ho una funzione che dovrebbe leggere da file riga per riga, la lettura si interrompe quando una riga non inizia con '>' o ''. Dovrebbe memorizzare le linee nel vettore e restituirle.
Questo è un codice:
vector in function - how to do return
#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;
string getseq(char * db_file) // gets sequences from file
{
string seqdb;
vector<string> seqs;
ifstream ifs(db_file);
string line;
//vector<char> 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 ++) restituisce:
fasta_parser.cpp: In function ‘std::string getseq(char*)’:
fasta_parser.cpp:32: error: conversion from ‘std::vector<std::basic_string<char, `std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ to non-scalar type ‘std::string’ requested`
Qualcuno ha qualche idea?
Edit: Come Skurmendel chiedere, sto aggiungendo intero codice a causa della violazione della sicurezza memoria dopo
l'esecuzione di codice compilato:
#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;
vector<string> getseq(char * db_file) // pobiera sekwencje z pliku
{
string seqdb;
vector<string> seqs;
ifstream ifs(db_file);
string line;
//vector<char> 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<string> 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<string> iterator type.
typedef vector<string>::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;
}
Cosa vuoi ritornare? Il vettore o la stringa? – SuperSaiyan
[Do not] (http://stackoverflow.com/questions/4881210/how-to-convert-a-string-to-a-ifstream/4881251#4881251) usa [while] (http: // stackoverflow. it/questions/4324441/getlinestreamobj-line-reads-last-line-multiple-times/4324667 # 4324667) (stream. [buon] (http://stackoverflow.com/questions/4874530/fstream-unix-problem-in -reading/4874650 # 4874650)()). –
@Thrustmaster: vector @Fred Nurk: perché e cosa devo invece usare? –