






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







#include
! ifstream my_input_file;! // an input file stream object ! ofstream my_output_file;! // an output file stream object ! my_input_file.open("input_data");!// open the file named "input_data" ! my_output_file.open("output_data");! // open the file named "output_data"
! ifstream my_input_file("input_data");! // create and open ! ofstream my_output_file("output_data");
! string filename; ! cin >> filename; ! ifstream my_input_file(filename);
! if (my_input_file.is_open()) { !! // can continue, file opened correctly !! }
! my_input_file >> int_var >> double_var;!
! my_output_file << "The integer is " << int_var << endl;
Handy member functions for character and line input
int get(); cin.get();
istream& get(char&); cin.get(char_variable);
istream& getline(char * array, int n); input_file.getline(buffer_char_array, buffer_length);
istream& getline(istream&, std::string&);
What can go wrong
A simple example
#include
bool get_int(istream& in_strm, bool& good_flag, int& x) {! ! bool continue_flag; ! ! in_strm >> x; ! if (in_strm.good()) { !! good_flag = true; !! continue_flag = true;! // can keep going !! } ! else if (in_strm.eof()) { !! cout << "End of file encountered." << endl; !! good_flag = false;!! // input value was not obtained !! continue_flag = false;! // time to stop !! } ! else if (in_strm.bad()) { !! cout << "Hard I/O error" << endl; !! good_flag = false; !! continue_flag = false;! // give up! !! } ! else if (in_strm.fail()) { !! cout << "Invalid input - skipping rest of line" << endl; !! in_strm.clear();! // don't forget! Must clear the stream to read it! !! char c; !! while (in_strm.get(c) && c != '\n'); // may hit eof while skipping !! good_flag = false;!! // value is not good !! if (in_strm.good())!! // did we hit eof or something else? !!! continue_flag = true;! // no - can keep going !! else { !!! continue_flag = false; // yes - time to stop !!! cout << "End of file or error while skipping rest of line." << endl; !!! } !! } ! else { !! cout << "Should be impossible to be here!" << endl; // for demo only! !! good_flag = false;! !! continue_flag = false; !! } ! return continue_flag; } --- input file --- 12
6t 89 x --- output --- value read is 12 value read is 34 Invalid input - skipping rest of line value read is 6 Invalid input - skipping rest of line value read is 89 Invalid input - skipping rest of line End of file or error while skipping rest of line. Done!