#include <iostream>
#include <vector>
using namespace std;
...
vector<float> x;
float xtmp;
int i,n;
...
while(1){
cin >> xtmp;
if(cin.fail()){ // Check for error.
if(cin.eof())break; // Check for end-of-file
cerr << "Error converting input data item.\n";
exit(1);
}
x.push_back(xtmp);
}
n = x.size();
cout << "There are " << n << " data points:\n";
for(i = 0; i < n; i++){
cout << "x[" << i << "] = " << x[i] << "\n";
}
In this loop each value is appended to the vector. The
cin.eof() function returns true when an end of file condition
is reached. Notice that we test after reading, and if an end
of file has been encountered, no value was read. Notice that we
protect ourselves from errors in data format conversion by using
cin.fail(), which returns true when an error occurred
(e.g. nonnumeric characters in the input) or an end-of-file was
reached.
The exercise for you is to complete the code above, compile it, and test it on both keyboard and file input. (For file input, just use input redirection with <). Create a file called data for redirection from standard input. Try entering nonnumeric values in place of numbers to see what happens.
Hand in your code and say what happens when you enter nonnumeric values.
If in completing the code in Exercise 1, you thought to prompt the user for input, you might consider that it would be better to send those prompts to cerr, rather than cout so if the user is redirecting output to a file, he/she would still see the prompts on the screen. So it isn't only error messages that should go to standard error.
In the answer file, explain where the error message appears when you redirect standard output to a file or pipe.
The online notes show how to do it with the standard header fstream. Modify the code you created in Exercise 1 so you read from the file.
If you want to see my example, see ~p6720/exercises/file_io/fileread.cc, but try to do it yourself first.
Hand in your version of the code.