// If you are not sure what some lines of code do, try looking back at
// previous example programs, notes, or ask a question.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Declare arrays of strings, ints, and chars to be inputted from
// the file
string strings[5] = {};
int ints[5] = {}, numInts, numChars;
char chars[5] = {};
// Declare variables to be used with our files
ifstream fin;
ofstream fout;
// Open the file in the input stream - note you must include
// the file extension (".txt").
fin.open("File IO - Example - In.txt");
// If we couldn't open the file, exit
if(!fin.good())
return 1;
// The actual data begins after a colon character, so ignore all data
// until after the colon.
fin.ignore(1000,':');
// Loop three times, inputting the strings from the file
for(int i = 0; i < 3; i++)
fin >> strings[i];
// Ignore the data until another colon
fin.ignore(1000,':');
// Input the number of ints to input, and loop that many times. Note
// that if this is greater than five, this will try to go off the end
// of the array and create an error.
fin >> numInts;
for(int i = 0; i < numInts; i++)
fin >> ints[i];
// Ignore the data until another colon
fin.ignore(1000,':');
// Input characters until the file says it cannot input any more data.
// Again, if this happens more than five times you will get an error,
// as 5 is the size of the chars array.
for(numChars = 0; fin.good(); numChars++)
fin >> chars[numChars];
// Decrement numChars, as it will have incremented one too many times.
// When fin.good() returns false, numChars will have already been incremented.
numChars--;
// Close the input file, as we are done with it
fin.close();
// Output the data to the console so we can see the input worked
// correctly
for(int i = 0; i < 3; i++)
cout << strings[i] << " ";
cout << endl;
for(int i = 0; i < numInts; i++)
cout << ints[i] << " ";
cout << endl;
for(int i = 0; i < numChars; i++)
cout << chars[i] << " ";
cout << endl;
// Open the output file - note this will create the file it it does not
// already exist. If it already exists, it will overwrite it.
fout.open("File IO - Example - Out.txt");
// Output the same results to the file.
// The process is exactly the same, except using "fout" instead of "cout."
for(int i = 0; i < 3; i++)
fout << strings[i] << " ";
fout << endl;
for(int i = 0; i < numInts; i++)
fout << ints[i] << " ";
fout << endl;
for(int i = 0; i < numChars; i++)
fout << chars[i] << " ";
fout << endl;
// Close the output file, as we are done with it.
fout.close();
cout << endl;
system("pause");
return 0;
}