c++ 将百鸡问题 保存到txt 文件中
#include<fstream>
#include<iomanip>
using namespace std;
int main(){
int i,j,k;
ofstream ofile; //定义输出文件
ofile.open("/Users/hyy/Desktop/table talk/myfile.txt"); //作为输出文件打开
ofile<<" 公鸡 母鸡 小鸡"<<endl; //标题写入文件
for(i=0;i<=20;i++)
for(j=0;j<=33;j++){
k=100-i-j;
if((5*i+3*j+k/3==100)&&(k%3==0)) //注意(k%3==0)非常重要
ofile<<setw(6)<<i<<setw(10)<<j<<setw(10)<<k<<endl; //数据写入文件
}
ofile.close(); //关闭文件
return 0;
}
c++ 读取百鸡txt 文件 显示
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
char a[28];
ifstream ifile; //定义输入文件
ifile.open("/Users/hyy/Desktop/table talk/myfile.txt"); //作为输入文件打开
int i=0,j,k;
while(ifile.get(a[i])){ //读标题,请对比cin.get(),不可用>>,它不能读白字符
if(a[i]=='\n') break;
i++;
}
a[i]='\0';
cout<<a<<endl;
while(1){
ifile>>i>>j>>k; //由文件读入数据
if(ifile.eof()!=0) break; //当读到文件结束时,ifile.eof()为真
cout<<setw(6)<<i<<setw(10)<<j<<setw(10)<<k<<endl; //屏幕显示
}
ifile.close(); //关闭文件
return 0;
}