ciao...
Ho scritto un programma in c++ per prendere in input delle stringhe da un file, ma nell'esecuzione mi a l'erroe segment faileur, programmo sotto linux!
Posto il codice dategli uno sguardo...
codice:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct elem {
string frase;
elem *ptr;
};
typedef struct elem * elem_ptr;
bool inserisci(elem_ptr& lista, string f);
int main ( int argc, char *argv[] ) {
if ( argc != 2) {
cerr << "Numero parametri non corretto" << endl;
return 0;
}
ifstream file;
cout << argv[1]<<endl;
file.open(argv[1], ios::in); // contrallare se il file è stato aperto
if (!file) {
cerr<<"Apertura file non riuscita\n";
exit(1);
}
string frase;
elem_ptr lista = NULL;
while (!file.eof() ) {
cout << "ciao" << endl;
getline(file,frase, '\n');
if (!inserisci(lista, frase)){
cerr << "Errore lettura del file\n" << endl;
exit (1);
}
cout << lista->frase << endl;
}
file.close();
while ( lista != NULL) {
cout << lista->frase << endl;
lista = lista->ptr;
}
return 0;
}
bool inserisci ( elem_ptr& lista, string f) {
cout << "fun"<<endl;
if ( lista == NULL) {
lista = new elem;
lista->frase = f;
lista->ptr = NULL;
} else {
elem_ptr temp = lista, prec_temp = NULL;
elem_ptr nuovo = new elem;
nuovo->frase = f;
while (lista != NULL && lista->frase > f) {
prec_temp = temp;
temp = temp->ptr;
}
if ( temp == lista) lista = nuovo;
else prec_temp->ptr = nuovo;
nuovo->ptr = temp;
}
return true;
}
[