建立文件输出
文件输出步骤总结:
1、建立输出流对象,并将输出流对象和输出文件名绑定:ofstream sss_out("sssout.txt");
2、向输出流输出元素,有两种方式,一种是直接输出:sss_out<<输出内容;
1 // Fig. 14.3: fig14_03.cpp 2 // Create a sequential file. 3 #include <iostream> 4 #include <string> 5 #include <fstream> // contains file stream processing types 6 #include <cstdlib> // exit function prototype 7 using namespace std; 8 9 int main() 10 { 11 12 ofstream sss_out("sssout.txt");// 建立输出流sss_out,并将输出流和文件sssout.txt绑定 13 14 // exit program if unable to create file 15 if (!sss_out) // overloaded ! operator 16 { 17 cerr << "File could not be opened" << endl; 18 exit(EXIT_FAILURE); 19 } // end if 20 21 cout << "Enter the account, name, and balance." << endl 22 << "Enter end-of-file to end input.\n? "; 23 24 int account; // the account number 25 string name; // the account owner's name 26 double balance; // the account balance 27 28 // read account, name and balance from cin, then place in file 29 while (cin >> account >> name >> balance) 30 { 31 sss_out << account << ' ' << name << ' ' << balance << endl;//向输出流输出元素 32 cout << "? "; 33 } // end while 34 } // end main
另一种可以建立输出流迭代器进行输出: ostream_iterator<int> out(out_xls," sss ");//sss为每个元素输出后输出的内容,即间隔。
1 #include<iostream> 2 #include<fstream> 3 #include<iterator> 4 using namespace std; 5 6 int main() { 7 ofstream out_xls("int.txt"); 8 //istream_iterator<int> in(cin); 9 ostream_iterator<int> out(out_xls," sss "); 10 int i; 11 while (cin >> i) { 12 *out++ = i; 13 } 14 15 }