// Lab 3 Lecture 2 // ----------------------- File Input and Output Example ---------------------- // Here we can see an example of both reading and writing // to a file. // Note that ofstream (output file stream) is used for // sending data from our program to the file. It is // handled almost identically to ifstream. // First we need to make an input file "input_file_name.txt" // and put your first and last name followed by your Jedi // level. Example: Jason Constanzo 32.5 // include our file stream library #include #include using namespace std; int main() { string firstName; string lastName; double jediLevel; // declare an input file stream variable and open the file ifstream fin; fin.open("input_file_name.txt"); // declare an output file stream variable and open the file. // *note - An output file will be created for you if // one does not already exist with the name given. ofstream fout; fout.open("output_file_name.txt"); // read data from the file fin >> firstName >> lastName >> jediLevel; // Here we output variables 'firstName','lastName', 'jediLevel' // and a string literal to the output file. // Notice that I use "fout" exactly the same as "cout". fout << firstName << " " << lastName << endl; fout << jediLevel << endl; fout << "You can also output literals to a text file " << 1337 << endl; // let the user know his data has been written to the file // by printing a message to the console (screen). cout << "Data has been written to 'output_file_name.txt'" << endl; // close files (dont forget about this!) fin.close(); fout.close(); return 0; }