C++语言程序设计 清华大学郑莉 输出流对象 输。 ofstream类支持磁盘文件输出 如果在构造函数中指定一个文件名,当构造这个文件 出 时该文件是自动打开的 流 ofstream myFile("filename"); ● 可以在调用默认构造函数之后使用open成员函数打开 文件 ofstream myFile;//声明一个静态文件输出流对象 myFile.open("filename"); //打开文件,使流对象与文件建立联系 。在构造对象或用open打开文件时可以指定模式 ofstream myFile("filename",ios_base:out ios base:binary);
C++语言程序设计 清华大学 郑莉 6 输出流对象 ⚫ ofstream类支持磁盘文件输出 ⚫ 如果在构造函数中指定一个文件名,当构造这个文件 时该文件是自动打开的 –ofstream myFile("filename"); ⚫ 可以在调用默认构造函数之后使用open成员函数打开 文件 ofstream myFile; //声明一个静态文件输出流对象 myFile.open("filename"); //打开文件,使流对象与文件建立联系 ⚫ 在构造对象或用open打开文件时可以指定模式 –ofstream myFile("filename", ios_base::out | ios_base::binary); 输 出 流
C++语言程序设计 清华大学郑莉 插入运算符 (<<) 输 ·插入(<<)运算符是所有标准C++数据 出 类型预先设计的。 流 ·用于传送字节到一个输出流对象
C++语言程序设计 清华大学 郑莉 7 插入运算符(<<) ⚫ 插入(<<)运算符是所有标准C++数据 类型预先设计的。 ⚫ 用于传送字节到一个输出流对象。 输 出 流
C++语言程序设计 清华大学郑莉 控制输出格式 输。控制输出宽度 为了调整输出,可以通过在流中放入setw操纵符或调用 出 width/成员函数为每个项指定输出宽度。 流。例11-1使用widthf控制输出宽度 #include <iostream> using namesoace std; int main(){ doub1 e values[]={1.23,35.36,653.7,4358.24}; for(int i =0;i<4;i++){ cout.width(10); 输出结果: cout <values[i]<endl; 1.23 } 35.36 return 0; 653.7 4358.24
C++语言程序设计 清华大学 郑莉 8 控制输出格式 ⚫ 控制输出宽度 –为了调整输出,可以通过在流中放入setw操纵符或调用 width成员函数为每个项指定输出宽度。 ⚫ 例11-1 使用width控制输出宽度 #include <iostream> using namesoace std; int main() { double values[] = { 1.23, 35.36, 653.7, 4358.24 }; for(int i = 0; i < 4; i++) { cout.width(10); cout << values[i] << endl; } return 0; } 输 出 流 输出结果: 1.23 35.36 653.7 4358.24
C++语言程序设计 清华大学郑莉 例:使用*填充 输 #include〈iostream> 出 using namespace std; 流 int main(){ doub1 e values[]={1.23,35.36,653.7,4358.24}; for(int i =0;i 4;i++){ cout.width (10); 输出结果: cout.fill('*'); ***1.23 cout <values[i]<'\n'; *****35.36 ***653.7 return 0; **4358.24
C++语言程序设计 清华大学 郑莉 9 例:使用*填充 #include <iostream> using namespace std; int main() { double values[]={ 1.23, 35.36, 653.7, 4358.24 }; for(int i = 0; i < 4; i++) { cout.width(10); cout.fill('*'); cout << values[i] << '\n'; } return 0; } 输 出 流 输出结果: ******1.23 *****35.36 *****653.7 ***4358.24
C++语言程序设计 清华大学郑莉 例11-2使用setw指定宽度 输 #include <iostream> #include<iomanip)》 出 #include <string> 流 using namespace std; int main({ doub1eva1ues[]={1.23,35.36,653.7,4358.24}; string names[]={"Zoot”,"Jimy,"A1”, "Stan"} for (int i 0;i 4;i++) 输出结果: cout <setw(6)<<names[i] Zoot 1.23 <setw(10)<<values[i]<endl; Jimmy 35.36 return 0; A1 653.7 Stan4358.24 10
C++语言程序设计 清华大学 郑莉 10 例11-2使用setw指定宽度 #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { double values[] = { 1.23, 35.36, 653.7, 4358.24 }; string names[] = { "Zoot", "Jimmy", "Al", "Stan" }; for (int i = 0; i < 4; i++) cout << setw(6) << names[i] << setw(10) << values[i] << endl; return 0; } 输 出 流 输出结果: Zoot 1.23 Jimmy 35.36 Al 653.7 Stan 4358.24