21.4 编程题
编程题主要是考核应聘者的C++编程的专业知识,这里选取了9个常见的编程示例进行介绍。
面试题61:结果输出到文件
问:文件中有一组整数,要求排序后输出到另一个文件中。
答:编写的程序如下所示。
01 #include<iostream> 02 #include<fstream> 03 #include<vector> 04 using namespace std; 05 06 void Order(vector<int>&data)//bubble sort 07 { 08 int count=data. size(); 09 int tag=false;//设置是否需要继续冒泡的标志位 10 for(int i=0;i<count;i++) 11 { 12 for(int j=0;j<count-i-1;j++) 13 { 14 if(data[j]>data[j+1]) 15 { 16 tag=true; 17 int temp=data[j]; 18 data[j]=data[j+1]; 19 data[j+1]=temp; 20 } 21 } 22 if(!tag) 23 break; 24 } 25 } 26 27 void main(void) 28 { 29 vector<int>data; 30 ifstream in("c:/data. txt"); 31 if(!in) 32 { 33 cout<<"file error!"; 34 exit(1); 35 } 36 int temp; 37 while(!in. eof()) 38 { 39 in>>temp; 40 data. push_back(temp); 41 } 42 in. close();//关闭输入文件流 43 Order(data); 44 ofstream out("c:/result. txt"); 45 if(!out) 46 { 47 cout<<"file error!"; 48 exit(1); 49 } 50 for(int i=0;i<data. size();i++) 51 out<<data[i]<<""; 52 out. close();//关闭输出文件流 53 }