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;
}
浙公网安备 33010602011771号