如题:2021年4月
分析
要是对文件读写不熟悉的话,还真不好弄……。
相关知识点的复习,详见:c++复习之文件操作
题目只要求向文件写,其实这也是教材一个程序。
解决:
#include <iostream>
#include <fstream>//先要包含相应的读写文件头文件
using namespace std;
int main()
{
char id[11], name[21];
int score;
ofstream outFile;//创建插入流对象
// outFile.open("../score.txt", ios::out);//这样是放到上一级目录了
// outFile.open("score.txt", ios::out);//这样写也可以,文件也是自动创建到.vscode一样的根目录下
outFile.open("./score.txt", ios::out); //以写方式打开文本文件,这个文件也是自动创建到和.vscode一个目录下
// outFile.open("c:\\tmp\\test.txt", ios::out);//文件存储到c盘temp文件夹下,绝对路径下
// outFile.open("tmp\\test.txt", ios::out);//用相对路径创建时,必须要存在tmp文件夹(这个文件夹要放在和.vscode一样目录下才能找到),文件可以在打开时自动创建
// outFile.open("c:/tmp/test.txt", ios::out);//这样写,错误,会创建文件失败
if (!outFile) {
cout << "创建文件失败" << endl;
return 0;
}
cout << "请输入: 学号 姓名 成绩 \n";//windows 先换行再按ctrl+z结束输入,可以看到目录下
while (cin >> id >> name >> score)//从键盘输入中提取出值
outFile << id << " " << name << " " << score << endl; //向文件中插入数据
outFile.close();
return 0;
}
如题 2020年8月
分析
就是基本的操作写法,一定要能默写出来。
解决
#include <fstream>
#include <iomanip>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
char buffer[100];
ifstream infile;
infile.open("address.txt", ios::in); //以读方式打开文件
if (!infile)
{
cout << "open err" << endl;
return 0;
}
while (!infile.eof())//不会写的地方,就是读出文件里的内容。
{
infile.getline(buffer, 50);
cout << buffer << endl;
}
return 0;
}
扩展
从文件读入信息。
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main(int argc, char const *argv[])
{
char id[11], name[21];
int score;
ifstream infile;
infile.open("./score.txt", ios::in);//以读的方式打开
if (!infile) {
cout << "open file err" << endl;
return 0;
}
cout << "学生学号 姓名\t 成绩" << endl;
while (infile >> id >> name >> score)//从文件中提取
cout << left << setw(10) << id << " " << setw(15) << name << " " << setw(3) << right << score << endl;
// cout << left << id << " " << name << " " << setw(3) << right << score << endl;
return 0;//需要设置流操纵符,所以需要包含iomainp头文件
//left,输出域左对齐
//setw,指定输出宽度为w个字符
//right,输出域右对齐
}