Having this:
#include <iostream>
#include <vector>
#include <istream>
using namespace std;
void read_vector(istream &in, vector<double> &vec)
{
if (in) //check wheter !in.fail() => but how can "cin" have error status??
{
vec.clear(); //also, clear the vector (general function)
double tmp;
while (in >> tmp)
{
vec.push_back(tmp);
}
in.clear(); //should be there any error?
}
}
int main()
{
double a, b;
vector<double> vec;
while (cin >> a >> b)
;
read_vector(cin, vec);
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << ' ';
}
cout << endl;
return 0;
}
I compile and try to give test values:
$./a.out
$1.2 3.4 5.6 7.8
$
NO output. the 1.2
should be saved to variable a
, the 3.4
should be saved to variable b
, and the rest stored to vector (via function read_vector
). I think since it is in while()
the bool condition of istream is still true.
What are condition to make istream false (I know of wrong value, EOF, or other signal).
Please give some practical example of
good()
,fail()
,bad()
,operator bool
andoperator!
-> according to https://en.cppreference.com/w/cpp/io/basic_ios/operator_boolBut there could be no "wrong" value (or other then type
double
) - how will thecin
recognize to stop input to operands (a
,b
), make thecin
wrong, and then continue to next functionread_vector
(so it eventually will populate the vector and I could see the result from the for loop)