Hi experts,
I am writing a small code to read input from a file, for example my
input file is:
X[i] Y[i] Z[i]
26.0 28.0 0.0
32.0 8.0 0.0
My code is:
#include<iostream>
using namespace std;
#include <fstream>
#include <iomanip>
#include <cstdlib> //exit prototype
void outputLine( double, double, double );
int main() {
//This program is trying to read the input from a certain format
double X[100];
double Y[100];
double Z[100];
//ifstream constructor opens the locations information file
ifstream inClientFile3( "Input-Location.txt", ios::in );
//Exit program if ifstream could not open file
if ( !inClientFile3 ) {
cerr << "Input file could not be opened!" << endl;
exit( 1 );
} //end if
//display each record in file
int i3in=0;
outClientFile1 << left << "Locations' Coordinates: " << endl;
inClientFile3.seekg( 30 ); //start read data stream from the second
line
while ( inClientFile3 >> x >> y >> z ){
outputLine( x, y, z );
}
return 0; // ifstream destructor closes the file
} // end main
void outputLine( double x, double y, double z ){
cout << setw( 10 ) << setprecision( 2 ) << right << x
<< setw( 10 ) << setprecision( 2 ) << right << y
<< setw( 10 ) << setprecision( 2 ) << right << z
<< endl;
};
It works fine. How ever, if i purposely change the data in the input
file (that should be of double type) to a character (meant an invalid
data type). For example I change the input file to:
X[i] Y[i] Z[i]
26.0 a 0.0
32.0 8.0 0.0
Then the program goes wrong, since it fails to read this type of data.
(It returns nothing for the whole stream)
My question is: Is there any way that can check if reading a line of
stream is successful? for example, when the program reads the "a", it
poses an error message?
Thank you very much for your commend and help.
Sonny