Handling of c++ files

Asked

Viewed 46 times

1

I’m having trouble manipulating a file. Always error on that part, specifically on that line "while(getline(alunosE, line)){", and I don’t know why.

ifstream alunosL;
string linha;
alunosE.open("alunos.txt");
if(alunosE.is_open()){
    while(getline(alunosE, linha)){
        cout << linha <<endl;
    }
    alunosE.close();
}
else {
    cout<<"erro!"<<endl;
}

1 answer

0


Use of the eof to know the end of the file:

while ( !alunosE.eof() ) {

That way the line reading will stay inside that while, see the full code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream alunosE;
    string linha;
    alunosE.open("alunos.txt");

    if(alunosE.is_open()){
        while ( !alunosE.eof() ) {
            getline(alunosE, linha);
            cout << linha << endl;
        }

        alunosE.close();
    }
    else {
        cout << "erro!" << endl;
    }
}

See online: https://repl.it/repls/DefiniteSunnyAnalysts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.