/*--- CS 111 - in-class examples from Week 14 Lecture 1 by: Sharon Tuttle last modified: 2023-04-25 ---*/ #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <fstream> // NEEEED this for file i/o!!! using namespace std; /*--- play with some C++ file input and file output ---*/ int main() { cout << boolalpha; //===== // let's write something to a file! ofstream latest_out_stream; ofstream append_out_stream; // open latest_out_stream for writing, // this version deletes previous contents latest_out_stream.open("latest_sounds.txt"); // open append_out_stream for appending, // this version causes next thing written // to be added to the end of the file // (appended to the file) append_out_stream.open("user_sounds.txt", ios::app); latest_out_stream << "Moo Baa" << endl << "La la la" << endl; latest_out_stream << "Hee haw!" << endl; string sound_from_user; cout << "Enter one more animal sound: " << endl; getline(cin, sound_from_user); latest_out_stream << sound_from_user << endl; append_out_stream << sound_from_user << endl; // CLASS and GOOD style: close your file // streams when you are done with them! latest_out_stream.close(); append_out_stream.close(); //===== // say I want to now READ from one of these files! // create an input file stream, and open it: ifstream in_stream; in_stream.open("latest_sounds.txt"); // don't need a cout prompt to read from a file... 8-) string next_sound; getline(in_stream, next_sound); cout << "read from latest_sounds.txt using " << "getline: " << endl << next_sound << endl; in_stream >> next_sound; cout << "read from latest_sounds.txt using " << ">>: " << endl << next_sound << endl; // CLOSE your input stream when you are done! in_stream.close(); //===== // say I want to write an array's contents to a file string tasty_dives[5] = {"Chum Bucket", "Top Burger", "No Brand Burger Stand", "Krusty Krab", "Lou's"}; ofstream dives_stream; dives_stream.open("my_dives.txt"); int index = 0; while (index < 5) { dives_stream << tasty_dives[index] << endl; index = index + 1; } dives_stream.close(); //===== // and let's demo reading everything from a file: ifstream dives_in_stream; dives_in_stream.open("my_dives.txt"); // hey, getline and >> return true if a read // succeeded, and false otherwise string next_dive; // so, while reading the next line succeeds, // print what was read to the screen while (getline(dives_in_stream, next_dive)) { cout << "I read: " << next_dive << endl; } dives_in_stream.close(); return EXIT_SUCCESS; }