-1

I am having problems reading from a txt file in c++.

The file is composed of lines, each line has a number of 4 digits that represents a year (e.g 1900) and movie titles separated by '#'.

the file's format is: number#movie title#movie title#movie title

example of lines:

1900#Sherlock Holmes Baffled#The Enchanted Drawing

1904#The Impossible Voyage

1918#Stella Maris#Mickey#Shifting Sands#A Dog's Life#Shoulder Arms

I want to read each line, save the year in a int variable, and each movie title in an array of string. Please help.

Here is my (wrong) code:

istream& operator >>(istream &is, Cronologia &crono){

    FechaHistorica fh;
    int anio;
    while(!is.eof()){
        char  c[1024];
        char  aux[4];

        is.read(aux,4);
        is.ignore('#');
        anio = atoi(aux);
        fh.setAnio(anio);

        cout << "\n" << anio << endl;

        while(is.getline(c,1024,'#')){

            fh.aniadeEventoHistorico(c);

        }    
    }
    return is;    
}

FechaHistorica is composed by: int n; Array of string

Ultraviolet
  • 3,000
  • 2
  • 19
  • 43
  • 3
    [`while(!is.eof())` is wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – melpomene Oct 31 '17 at 08:52
  • 1
    Read the entire line using [std::getline](http://en.cppreference.com/w/cpp/string/basic_string/getline) then use common [parsing](https://en.wikipedia.org/wiki/Parsing) techniques on that line. – Basile Starynkevitch Oct 31 '17 at 09:54

2 Answers2

0

What about this kind of function:

string test="1918#Stella Maris#Mickey#Shifting Sands";
vector<string> buffer;

size_t found = 0;
while ( found <= test.size() ){
    found = test.find('#')
    buffer.push_back(test.substr(0, found) );
    test.erase(test.begin(), test.begin()+(found+1) );
}

It returns vector like buffer = [1918, Stella Maris, ....], and for the txt reading

ifstream f( path );
string line;

while (getline (f,line) ){
    // goes line by line, return line as string
}

f.close()
Buddy
  • 39
  • 3
0

In your code is.ignore('#'); is wrong. See here. So use as following

if (iss.peek() == '#') {
    iss.ignore();
}

And at the end while(is.getline(c,1024,'#')){ will not end until the end of file. So I think, you read the whole line first and then process it like below.

string line;
while(getline(is, line)){

    istringstream iss(line);
    char  c[1024];
    char  aux[4];

    iss.read(aux,4);
    if (iss.peek() == '#') {
        iss.ignore();
    }
    anio = atoi(aux);
    fh.setAnio(anio);
    cout << "\n" << anio << endl;

    while(iss.getline(c,1024,'#')){
        cout << c << endl;
    }
}
Ultraviolet
  • 3,000
  • 2
  • 19
  • 43