方法一:文件重定向
#define _CRT_SECURE_NO_WARNINGS
#define LOCAL
#include <iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("data.out", "w", stdout);
#endif
int x;
scanf("%d", &x);
printf("%d\n", x);
return 0;
}
事先在对应的文件夹内手动建立两个txt文件
in.txt读入数据,在data.out文件输出结果
方法二:直接用文件输入输出
#define _CRT_SECURE_NO_WARNINGS
#define LOCAL
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
FILE *fin,*fout;
fin=fopen("in.txt","rb");
fout=fopen("data1.out","wb");
int x;
fscanf(fin,"%d",&x);
int y=2*x;//位置不能放错,先从文本读入x的值,再初始化y
fprintf(fout,"%d",y);
fclose(fin);
fclose(fout);
return 0;
}
就是在原有基础上定义了两个FILE指针用于读入和输出,scanf和printf对应fscanf和fprintf,结尾需要fcolse。