Your biggest issue is that >>
skips leading whitespace, so it doesn't differentiate between a ' '
(space) or '\n'
-- it's just whitespace. To handle it correctly, you need to read each line into a std::string
and then create a std::stringstream
from the line.
Then read your three double
values from the std::stringstream
with >>
. That way you can read no more double
values than are present in the line. Otherwise if you just try and use >>
, you will happily read 2 double
values from one line and the third from the next without any indication of that happening.
You next need your function to indicate success/failure of reading the three double
values from the line. A return type of bool
is all you need. If you read three valid double
values, return true
and do your calculations()
otherwise, if you return false
, stop trying to read from the file.
A short example would be:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
bool read3doubles (std::ifstream& f, double& a, double& b, double& c)
{
std::string line {}; /* std::string to hold line */
if (getline (f, line)) { /* if line read from file */
std::stringstream ss(line); /* create stringstream from line */
if (ss >> a >> b >> c) /* if 3 doubles read from line */
return true; /* return true */
}
return false; /* otherwise, return false */
}
void calculations (double& a, double& b, double& c)
{
std::cout << a << " " << b << " " << c << '\n';
}
int main (int argc, char **argv) {
if (argc < 2) { /* validate at least 1 argument given */
std::cerr << "error: insufficient number of arguments.\n"
"usage: " << argv[0] << " <filename>\n";
return 1;
}
std::ifstream f (argv[1]); /* open file-stream with 1st argument */
double a, b, c;
if (!f.good()) { /* validate file open for reading */
std::cerr << "errro: file open failed '" << argv[1] << "'.\n";
return 1;
}
while (read3doubles(f, a, b, c)) /* while 3 doubles read from file */
calculations (a, b, c); /* do your calculation */
}
(note: the calculations()
function just outputs the three doubles when successfully read)
Example Use/Output
Using your input in the file dat/3doubles.txt
, you would have:
$ ./bin/read3doubles dat/3doubles.txt
1 1 1
1.2 -2.3 0.4
-2 -3 -4
0 -2 8.85
Let me know if you have further questions.