I am new to C++ and want to add error checking to my code plus I want to make sure I'm using good coding practices. I read a line from an ASCII file into a string using:
ifstream paramFile;
string tmp;
//open input file
tmp.clear();
paramFile >> tmp;
//parse tmp
How can I error check to make sure the input file read was successful?
I'm seeing much more complicated ways of reading from an ASCII file out there. Is the way I'm doing it "safe/robust"?
paramFile >> tmp;
If the line contains spaces, this will not read the whole line. If you want that usestd::getline(paramFile, tmp);
which reads up until the newline. Basic error checking is done by examining the return values. For example:operator>>
andstd::getline
both return a reference to the stream. The stream evaluates to a boolean value which you can check after the read operation. The above example will only evaluate to true if the read was successful.Here is an example of how I might make your code: