intmain()fstream outFile("numbers.txt",ios::out);int nums[3][3] = 1234, 3, 567, 34, 8, 6789, 124, 2345, 89] ;for(introw=0;row<3;row++)1/向文件输出三行for(intcol=0;col<3;col++)outFile<< setw(10)<<nums[row][col] <<"" ;outFile<<endl;outFile.closeO;returnO;2-5.cpp
int main( ) { fstream outFile("numbers.txt", ios::out ); int nums[3][3] = { 1234, 3, 567, 34, 8, 6789, 124, 2345, 89 } ; for( int row = 0 ; row < 3 ; row++ ) // 向文件输出三行 { for( int col = 0 ; col < 3 ; col++ ) outFile << setw(10) << nums[row][col] <<" " ; outFile << endl ; } outFile.close( ); return 0; } 2-5.cpp
采用>>从文件读数据2.3.3回顾C语言中例2-6:从文件中读入4个字符串。如何读文件#include <iostream>using namespace std;#include <fstream>#include<cstdlib>void main()fstream dataFile:char name [81];
17 2.3.3 采用 >> 从文件读数据 • 例2-6:从文件中读入4个字符串。 #include <iostream> using namespace std; #include <fstream> #include <cstdlib> void main( ) { fstream dataFile; char name [81]; 回顾C语言中 如何读文件
dataFile.open("demofile.txt",ios::in);if (!dataFile)cout<<"Fileopen error!"<<endl;exit(0);for(int count = O; count < 4; count++)dataFile>> name;cout << name<< endl;dataFile.closeO;2-6.cpp
dataFile.open("demofile.txt", ios::in); if ( !dataFile) { cout << "File open error!" << endl; exit(0); } for(int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close( ); } 2-6.cpp
检测文件结束2.3.4eof()成员函数报告文件结尾。回顾C语言中如何检测结束注意:eof(endoffile)意味着文件指针已经超出了最后一个数据的范围,无数据可读if(inFile.eofO)while(!inFile.eofO)inFile >>var;inFile.close();9
19 2.3.4 检测文件结束 • eof ( ) 成员函数报告文件结尾。 • 注意: eof(end of file)意味着文件指针已经超出 了最后一个数据的范围,无数据可读. while( ! inFile.eof ( )) inFile >> var; if (inFile. eof ( )) inFile.close( ); 回顾C语言中 如何检测结束
例2-7对例2-6改进:读入文件中所有字符串。void main()// openfilewhile(! dataFile.eofO)dataFile>> name;if(dataFile.failO)break;cout<<name<<"ln"dataFile.closeO;2-7.cpp
void main( ) { . // open file while( ! dataFile.eof( )) { dataFile >> name ; if(dataFile.fail( )) break; cout << name << "\n"; } dataFile.close( ); } 例2-7 对例2-6 改进:读入文件中所有字符串。 2-7.cpp