Rule number 1 on reading data from a file: do not trust the contents of the file. You never know with absolute certainty what is in a file until you read it.
However, one correct way to read data lines from a file, where each line consists of several fields with space separators, would be to use a combination of getline and stringstream :
std::string line; while (std::getline(infile, line)) { std::stringstream ss(line); int a, b, c; if (ss >> a >> b >> c) {
In English, we get each line from a file stream using getline , then parse the string into three integers using stringstream . This allows us to be sure that each line is formatted correctly.
We test to ensure that integers are successfully extracted before we add them to arrays to ensure that arrays always only have valid data.
There is another error handling:
- In the example, if fetching integers from a string fails, we simply ignore that string; It might be a good idea to add logic to interrupt the process or report an error.
- After we get three integers, we ignore the rest of the line; it might be a good idea to add checks to ensure that there is no more data in the line after the required integers, depending on how strict the file formatting should be.
- After we finish reading the file, we need to check that
eof() installed, and not fail() or bad() ; if one of these two flags is set, an error occurred while reading the file.
source share