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操纵符或调用1dh成 出 setw和width都不截断数值 流 识松必款案随其后的域,在域输出结束后宽度恢复默 例11-1使用width控制输出宽度 #include <iostream using namesoace std; int main(f double 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 return 0; 35.36 653.7 日 4358.24
C++语言程序设计 8 控制输出格式 控制输出宽度 –为了调整输出,可以通过在流中放入setw操纵符或调用width成 员函数为每个项指定输出宽度。 –setw和width都不截断数值 –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++语言程序设计 例:使用*填充 输 ● 缺省为空格 出 使用setfi11操纵符或fi11成员函数设置填充字符 ● 持久影响 流 #include <iostream> using namespace std: int mainO doub1eva1ues[]={1.23,35.36,653.7,4358.24}: cout.fill('*): for(int i=0;i 4;i++){ 输出结果: cout.width (10): ***1.23 cout <values[i]<<'n'; *****35.36 ***653.7米 return 0; ***4358.24
C++语言程序设计 9 例:使用*填充 缺省为空格 使用setfill操纵符或fill成员函数设置填充字符 持久影响 #include <iostream> using namespace std; int main() { double values[]={ 1.23, 35.36, 653.7, 4358.24 }; cout.fill('*'); for(int i = 0; i < 4; i++) { cout.width(10); 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(){ doub1 e values[]={1.23,35.36,653.7,4358.24}; string names[]={"Zoot”,"Jimmy”,"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; Al 653.7 Stan4358.24
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