1

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?

Benoit
  • 76,634
  • 23
  • 210
  • 236
JuanPablo
  • 23,792
  • 39
  • 118
  • 164

2 Answers2

2

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.

Benoit
  • 76,634
  • 23
  • 210
  • 236
0

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.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299