The stream manipulators can be used to format console output as well as file output.
You have used the stream manipulators to format output to the console in Section 4.10, “Formatting Console Output.” You can use the same stream manipulator to format output to a file. Listing 13.5 gives an example that formats the student records to the file named format- tedscores.txt.
Listing 13.5 WriteFormattedData.cpp
1 #include <iostream>
2 #include <iomanip>
3 #include <fstream>
4 using namespace std;
5
6 int main()
7 {
8 ofstream output;
9
10 // Create a file
11 output.open(“formattedscores.txt”);
12
13 // Write two lines
14 output << setw(6) << “John” << setw(2) << “T” << setw(6) << “Smith”
15 << ” ” << setw(4) << 90 << endl;
16 output << setw(6) << “Eric” << setw(2) << “K” << setw(6) << “Jones”
17 << ” ” << setw(4) << 85;
18
19 output.close();
20
21 cout << “Done” << endl;
22
23 return 0;
24 }
The contents of the file are shown below:
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.