// This file contains some examples of stream manipulation with cin, cout, and // file-based streams // // some common istream operations: // ifstream input(name); initializes ifstream to read from given file // ofstream output(name); initializes ofstream to write to given file // stream >> x; read (extract) x from given input stream // stream << x; write (insert) x to given output stream // getline(input, str) read into str one line from input // stream.open(name); opens the stream to the given file // stream.close() closes the stream // istringstream input(str) make an input stream from the given string // ostringstream output() make an output stream from the given string // stream.str() convert an ostringstream to a string // stream.good() is the stream in a good state? // stream.clear() clear all error flags for the stream // stream.eof() is the end-of-file flag set for this stream // stream.get(ch) reads one char from the stream, setting ch // stream.peek(ch) returns next character to be read #include #include #include #include #include using namespace std; // uses the given prompt to prompt the console user for an int and keeps // prompting until the user provides a legal int int read_int(const string & prompt) { cout << prompt; int n; while (!(cin >> n)) { cout << "That wasn't an int" << endl; string dummy; cin.clear(); getline(cin, dummy); cout << prompt; } return n; } // processes a file of int values reporting the numbers, their sum, and any // illegal tokens it encounters in the file void process_file(string name) { ifstream input(name); int sum = 0; int n; while (!input.eof()) { if (input >> n) { cout << "next int = " << n << endl; sum += n; } else { input.clear(); string bad; if (input >> bad) { cout << "skipping illegal token " << bad << endl; } } } cout << "sum of file entries = " << sum << endl; } // returns a string version of the given int string int_to_string(int n) { ostringstream out; out << n; return out.str(); } void count_words(string name) { cout << "word counts for file " << name << endl; ifstream input(name); string line; int line_count = 0; while (getline(input, line)) { line_count++; istringstream data(line); string token; int word_count = 0; while (data >> token) { word_count++; } cout << " line # " << line_count << " has " << word_count << " word(s)" << endl; } } int main() { int n = read_int("give me an int: "); cout << n << endl; cout << endl; process_file("data.txt"); cout << endl; ofstream output; output.open("foo1.txt"); output << "what fun" << endl; output.close(); output.open("foo2.txt"); output << "even more fun" << endl; int x = 3, y = 4; string s = "x = " + int_to_string(3) + ", y = " + int_to_string(4); cout << s << endl; cout << endl; count_words("jabberwocky.txt"); return 0; }