C++ Ifstream
Home ~ Personal ~ Resume ~ Code and Classes and Research ~ Favorite Links ~ Comics Pit
Here are some common tasks with their implementations. There is a good reference for this, but it doesn't include these examples.
double v1, v2, v3;
in >> v1 >> v2 >> v3;
if (!in.fail()) {
// The values were properly parsed
do_stuff(v1, v2, v3);
} else {
// There was a problem. Depending on what you want to do, you can simply
ignore it; however, you need to at least clear the error state.
in.clear();
}
#includeThis will set numwords to be one extra than it should be. The problem is that the stream won't hit the end of file (EOF) until you try to read something that isn't there. There are a couple of different ways around this. The first involves adding an extra check before you increment numworkds.#include #include using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Usage: "<< argv[0] << " filename\n"; return 1; } char* filename = argv[1]; ifstream in(filename); int numwords = 0; while(in.good()) { string token; in >> token; numwords++; } cout << filename << " had " << numwords << " words in it\n"; return 0; }
while(in.good()) {
string token;
in >> token;
if (!in.eof()) numwords++;
}
The second forces the reading of the next token before the loop iterates.
string token;
in >> token;
while(in.good()) {
numwords++;
in >> token;
}
Depending on what you are trying to do, the first method has better scoping.
You can also replace in.eof() with in.good() to catch other errors, but it
seems kind of odd that you would have to have two calls to check the state of
the stream. By rewriting the loop you can get down to a single check. This
check could also be expanded to distinguish between bad reads or the end of
the file.
for(;;) {
string token;
in >> token;
if (in.good()) {
numwords++;
} else if (in.eof()) {
break;
} else {
cerr << "Error reading string\n";
break;
}
}