// Bob Myers // // sample of using file input. // Try this out on the file "testinput" // Notice the order of items in the file, and compare that with the // order of reads using the ifstream object called in1 #include #include // for setw #include // for ifstream, ofstream using namespace std; int main() { char filename[25]; // initialize a string for filename int numList[20]; char name[30]; double x; char word1[15]; char word2[15]; char word3[15]; ifstream in1; // initialize a file input do { in1.clear(); cout << "Please enter the name of the input file.\n"; cout << "Filename: "; cin >> setw(25) >> filename; in1.open(filename); if (!in1) { cout << "That is not a valid file. Try again!\n"; } } while (!in1); // get some input in1 >> x; // first reads a double in1.get(); in1.getline(name, 30); // then a string (up to '\n') for (int i = 0; i < 20; i++) // then a list of integers in1 >> numList[i]; in1 >> word1; in1 >> word2; in1 >> word3; // then three words in1.close(); // output the stuff that we read from the file to a new output file ofstream fout; fout.open("output.txt"); /* Try it in append mode instead fout.open("output.txt", ios::app); */ if (!fout) { cerr << "** error opening output file\n"; return 0; } fout << "\nThe name was " << name << endl; fout << "The decimal was " << x << endl; fout << "Here is every other number from the integer list:\n"; for (int i = 0; i < 20; i+=2) fout << numList[i] << ' '; fout << endl; fout << x << " times " << numList[3] << " = " << x * numList[3]; fout << '\n' << name << "'s favorite food is "; fout << word1 << ' '<< word2 << ' ' << word3; fout << "\n\nI/O sample complete\n"; fout.close(); fout.open("out2.txt"); if (!fout) { cerr << "** error opening output file\n"; return 0; } fout << "Logfile: iosample\n"; fout << "Yadda yadda yadda\n"; fout.close(); return 0; }