C++流项目练习
按照指定格式读取文件
#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
using namespace std;
int main(void)
{
ifstream inFile;
string line;
char name[32];
int age;
inFile.open("user.txt");
while (1)
{
getline(inFile, line);
if (inFile.eof())
{
break;
}
sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name, sizeof(name), &age);
cout << "姓名:" << name << "\t\t年龄" << age << endl;
}
inFile.close();
system("pause");
return 0;
}
按照指定格式写文件
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int ereq(void)
{
string name;
int age;
ofstream outFile;
//打开文件
outFile.open("user.txt");
while (1)
{
cout << "请输入姓名:";
cin >> name;
if (cin.eof())
{
break;
}
cout << "请输入年龄:";
cin >> age;
stringstream s;
s << "姓名:" << name << "\t\t\t年龄:" << age << endl;
outFile << s.str();
}
outFile.close();
system("pause");
return 0;
}
写文本文件
#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
using namespace std;
int writeFile(void)
{
string name;//姓名
int age;//年龄
ofstream outFile;
//打开文件
outFile.open("user.txt", ios::out | ios::trunc);
while (1)
{
//输入姓名
cout << "请输入姓名:";
cin >> name;
//判断是否输入
if (cin.eof())
{
break;
}
outFile << name << "\t";
//输入年龄
cout << "请输入年龄:";
cin >> age;
outFile << age << endl;
}
outFile.close();
system("pause");
return 0;
}
读文本文件
#include <iostream>
#include <Windows.h>
#include <string>
#include <fstream>
using namespace std;
int readFile(void)
{
string name;
int age;
ifstream outFile;
outFile.open("user.txt");
while (1)
{
outFile >> name;
if (outFile.eof())
{
break;
}
cout << name << "\t";
outFile >> age;
cout << age << endl;
}
outFile.close();
system("pause");
return 0;
}
二进制读文件
#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
using namespace std;
int er(void)
{
ifstream inFile;
string name;
int age;
inFile.open("user.dat", ios::in | ios::binary);
while (1)
{
inFile >> name;
if (inFile.eof())
{
break;
}
cout << name;
char tmp;
inFile.read(&tmp, sizeof(tmp));
inFile.read((char*)&age, sizeof(age));
cout << age << endl;
}
inFile.close();
system("pause");
return 0;
}
二进制写文件
#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
using namespace std;
int erOutFile(void)
{
ofstream outFile;
string name;
int age;
outFile.open("user.dat", ios::out | ios::trunc | ios::binary);
while (1)
{
cin >> name;
outFile << name;
if (cin.eof())
{
break;
}
cin >> age;
outFile.write((char*)&age, sizeof(age));
}
outFile.close();
system("pause");
return 0;
}
posted on 2022-09-09 15:55 会飞的鱼-blog 阅读(15) 评论(0) 编辑 收藏 举报 来源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下