還記得我們之前提到的頭文件<iomanip>嗎?那時候我們格式化了控制台輸出,那么同理,我們也可以將cout換為一個fstream或ofstream對象以格式化輸出到文件。如果想不起<iomanip>頭文件,可以回顧這篇博客C++格式化控制台輸出。
下面我們來舉個例子:
#include <iostream> #include <iomanip> #include <fstream> using namespace std; int main() { ofstream output; output.open("demo.txt"); output << setw(2) << "I" << setw(6) << "like" << setw(10) << "C++" << endl; output << setw(2) << "He" << setw(6) << "like" << setw(10) << "Java" << endl; return 0; }
運行結果:
這里只使用了setw函數來設置了空格,也可以使用其他函數來格式化輸出。