JuanPablo
JuanPablo

Reputation: 24764

Read and split with c++

With c++ I read a file

a;aa a;1 
b;b bb;2  

and split the lines, with this code

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
vector<string> split(string str, string separator)
{
    int found;
    vector<string> results;
    found = str.find_first_of(separator);
    while(found != string::npos) {
        if(found > 0) {
            results.push_back(str.substr(0,found));
        }
        str = str.substr(found+1);
        found = str.find_first_of(separator);
    }
    if(str.length() > 0) {
        results.push_back(str);
    }
    return results;
}
void lectura()
{
    ifstream entrada;
    string linea;
    vector<string> lSeparada;
    cout << "== Entrada ==" << endl;
    entrada.open("entrada.in");
    if ( entrada.is_open() ) {
        while ( entrada.good() ) {
            getline(entrada,linea);
            cout << linea << endl;
            lSeparada = split(linea,";");
            cout << lSeparada[0] << endl;
        }
        entrada.close();
    }
    exit(0);
}

but I get trash in the output

== Entrada ==
a;aa a;1
a
b;b bb;2
b

b a;11?E????aa a!(GXG10F????11?GXGb bb;21F????b bb!?G1?F????2??

Why do I get this trash?

Upvotes: 1

Views: 575

Answers (2)

Benoit
Benoit

Reputation: 79175

Your last call to getline leaves linea empty. With an empty line as input, split will return an empty vector (the test length() > 0 will be false). Trying to dereference the first element (lSeparada[0]) then invokes undefined behaviour.

Maybe the input file does not contain an empty line, but the last call to getline() will fail. You should test whether the istream& returned by std::getline() is good with while(getline(entrada,linea)) instead of while(entrada.good()) getline(entrada,linea). This might solve your problem.

Upvotes: 2

Ferruccio
Ferruccio

Reputation: 100648

One problem I noticed is that you probably want to use:

results.push_back(str.substr(0, found - separator.length()));

in split() so that the separator string is not included in your output.

Upvotes: 0

Related Questions