In your constructor, you do not test whether the file opened successfully. Therefore, you have no idea if the file opened successfully. Thus, your couteverything
method can't distinguish EOF from "failed to open." You might consider adding a check:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
if (!db_file.is_open() || !db_file.good()) {
// put an error message here, or throw an exception. Up to you.
}
}
Once you're in couteverything()
, presumably you want to loop over the entire file. You need a loop for that, not an if
statement. Something like this:
while (getline(db_file, line)) {
cout << line;
cout << "ok";
}
Even if you did not want to loop here (in which case coutnextline()
might be a better name for the method), you still want to test the result of getline()
directly, rather than testing good()
and is_open()
before each read. You need to test whether getline()
succeeds, otherwise your code will try to process one line beyond EOF or a read error.
if (getline(db_file, line)) {
cout << line;
cout << "ok";
}
If you do only want to output a line at a time, I'm not sure how the code that calls this would know when to stop. But, that's a different problem. (Hint: You could solve that by returning a bool
from this line-at-a-time method.)