Course Web Pages

Related Links

Free eBooks


File i/o and vectors

The videos below demonstrate the use of file input and output. Also included are demonstrations of the use of vectors. Examples are taken from Bruce Eckel's free online book, Thinking in C++, and from Dawson's Beginning C++ book. 

line-by-line copying of a file

 scopy.cpp


reading a whole file into one string

 fill_string.cpp


A new version of Hero's Inventory with a vector

 heros_inventory2.cpp


reading a file into a vector

 fill_vector.cpp


getting whitespace-separated words from a file

 get_words.cpp


a vector with elements of type int

 int_vector.cpp


Exercises

Complete these exercises from Thinking in C++, 2nd edition, Volume 1:

  1. Create a program that opens a file and counts the whitespace-separated words in that file.Create a program that counts the occurrence of a particular word in a file (use the string class's operator '==' to find the word).
  2. Change fill_vector.cpp so that it prints the lines (backwards) from last to first.
  3. Change fill_vector.cpp so that it concatenates all the elements in the vector into a single string before printing it out, but don't try to add line numbering.
  4. Display a file a line at a time, waiting for the user to press the "Enter" key after each line.
  5. Create a vector<float> and put 25 floating-point numbers into it using a for loop. Display the vector.
  6. Create three vector<float> objects and fill the first two as in the previous exercise. Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. Display all three vectors.
  7. Create a vector<float> and put 25 numbers into it as in the previous exercises. Now square each number and put the result back into the same location in the vector. Display the vector before and after the multiplication.