Why can’t I read that file with fstream?

Asked

Viewed 42 times

1

I am studying the input and output C++ files part, but I find myself with a small problem. I’m trying to get the program to read a file called "name.txt" with 10 names inside it, but for some reason it’s not able to do that, when I do the test it doesn’t even get into if/Else. He creates the file with the names normally but can’t print what’s inside it

fstream arquivo;
arquivo.open("nome.txt", ios::out);
arquivo << "Diego\n";
arquivo << "Thales\n";
arquivo << "Vitor\n";
arquivo << "Lais\n";
arquivo << "Rodrigo\n";
arquivo << "Karen\n";
arquivo << "Larissa\n";
arquivo << "Thiago\n";
arquivo << "Gabriel\n";
arquivo << "Arthur\n";

string line;
arquivo.open("nome.txt", ios::in);
if(arquivo.is_open())
{
    while(getline(arquivo, line)) {
        cout << line << endl;
    }
}
else
{
    cout << "erro: não foi possivel encontrar os nomes";
}
arquivo.close();
return 0;

}

  • 2

    You should not close the file after writing it to just then open it as read?

  • that’s right, I forgot. Thank you!

No answers

Browser other questions tagged

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