|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
C++快速入门第11讲 Fishoil 程序代码
在之前的一个帖子评论区下面找到的代码,有一处报错,已修改,VC++6.0编译运行通过 分享给需要的鱼油~
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
struct FishOil //定义一个结构
{
std::string name; //结构里面有三个变量,两种类型
std::string uid;
char sex;
};
bool InitFishC(); //初始化,抽象出来,把每个功能抽象成一个个函数
bool ReadFishC(); //读取数据
void RecordFishC(); //记录数据
bool WriteFishC(FishOil *Oildata);//写入数据//主函数
int main()
{
int i;
InitFishC();//初始化,
while( 1 )
{
std::cout << "请选择需要进行的操作:\n";
std::cout << "1.打印数据到屏幕\n";
std::cout << "2.录入数据\n";
std::cout << "3.退出程序\n";
std::cin >> i ; //用户界面输入的选择数字i传递给cin
switch(i) //switch事件,包含用户输入的三个选择
{
case 1:
if( ReadFishC() ) //如果ReadFishC()函数的返回值为真,则打印成功读取文件,否则打印读取文件失败;
std::cout << "成功读取文件\n\n" ;
else
std::cout << "读取文件失败\n\n" ;
break;
case 2:
RecordFishC();
break;
case 3:
return 0;
}
}
//std:: cout << "初始化失败\n\n";
return 0;
}
//初始化
bool InitFishC()
{
//FishOil OilInit = {"小甲鱼", "fishc00001", 'M'};辣鸡VC6.0这么写编译出错,改成下面的形式
FishOil OilInit;
OilInit.name = "小甲鱼";
OilInit.uid = "fishc00001";
OilInit.sex = 'M';//在文件中写入内容
//char* path="FishC.txt";
//这种也是一种创建文本的方式;
//std::fstream
//Fish("FishC.txt",std::ios::in|std::ios::out);
if(WriteFishC(&OilInit) ==true)
{
std::cout << "初始化成功\n";
}
else
{
std::cout<<"初始化失败\n";
}
return 0;
}
bool ReadFishC()
{
std::string temp;
std::ifstream fileInput("FishC.txt");
if( fileInput.is_open() )
{
std::cout << "\n正在输出记录数据...... ";
for( int i=0; i <= 100; i++ ) // 打印百分比
{
std::cout.width(3);
std::cout << i << "%";
Sleep(50);
std::cout << "\b\b\b\b";
}
std::cout << "\n\n";
std::cout << " 姓名 " << " 身份证 " << " 性别 " << "\n\n";
while( std::getline( fileInput, temp ) )
{
std::cout << temp << " ";
std::cout << "\n";
}
std::cout << "\n\n";
return true;
}
else
return false;
}
void RecordFishC()
{
char goon, Save;
FishOil OilData;
FishOil *pOilData; goon = 'Y';
while( 'Y' == goon||'y'==goon )
{
std::cout << "请输入鱼C账号: ";
std::cin >> OilData.name;
std::cout << "请输入鱼C身份证:";
std::cin >> OilData.uid;
std::cout << "请输入性别:";
std::cin >> OilData.sex;
std::cout << "录入成功, 请问需要保存吗?(Y/N)";
std::cin >> Save;
if( 'Y' == Save||'y'==Save )
{
pOilData = &OilData;
if( WriteFishC( pOilData ) )
std::cout << "成功写入文件^_^\n";
else
std::cout << "写入文件失败T_T\n";
}
else
{
return;
}
std::cout << "/n请问需要再次录入吗?(Y/N)";
std::cin >> goon;
}
}
bool WriteFishC(FishOil *pOilData)
{
std::ofstream fileOutput("FishC.txt", std::ios::app); // std::ios::app用来说明在老数据追加新数据
if( fileOutput.is_open() )
{
fileOutput << pOilData->name << " ";
fileOutput << pOilData->uid << " ";
fileOutput << pOilData->sex << "\n";
fileOutput.close();
std::cout << "数据成功保存到FishC.txt\n\n";
return true;
}
else
{
std::cout << "保存失败T_T\n";
return false;
}
} |
|