c++的简单文件输入输出
需要用到头文件 fstream
ofstream outfile(" ",ios::out)
ifstream infile(" ",ios::in)
QUESTION
从文件 in.dat 中读入两个数,输出他们的和到 out.dat 中
#include<fstream>
using namespace std;
int main()
{
ifstream infile("in.dat",ios::in);
ofstream outfile("out.dat",ios::out);
int a,b;
infile>>a>>b;
outfile<<a+b<<endl;
return 0;
}
—>发现没有 infile outfile 与 cin cout 用法是一样的有没有<—
所以可以将代码修改如下:
#include<fstream>
//#include<iostream>
using namespace std;
int main()
{
ifstream cin("in.dat",ios::in);
ofstream cout("ot.dat",ios:out);
int a,b;
cin>>a>>b;
cout<<a+b<<endl;
return 0;
}
注意:iostream 一定要注释掉,否则会引起 cin cout 的意义不明确
还可以像下面这样:
//#include<iostream>
#include<fstream>
using namespace std;
#define infile cin
#define outfile cout
int main()
{
ifstream infile("in.dat",ios::in);
ofstream outfile("ot.dat",ios:out);
int a,b;
cin>>a>>b;
cout<<a+b<<endl;
return 0;
}
这样子只是方便去复制文件输入输出语句 手动滑稽
对拍程序
对拍我们需要用的东西
1.你的代码
首先,你需要先写出你代码,并生成一个 .exe 文件(可执行文件)
这个程序你不知道它的对错,bug等
2.你认为正确的代码
然后,你需要一份正确的代码。可以是暴力程序,或者,是已经AC的代码,要不然,就是你认为是对的代码。同样的需要生成一个 .exe 文件。
3.数据生成器
你需要写一个数据生成的程序,然后生成 .exe 。
4.对拍模板
然后新建一个txt文本,打开,输入以下内容
@echo
:loop
makedata.exe
yours.exe
ac.exe
if %errorlevel%==0 goto loop
pause
:end
例子:A+B 问题
1. 我的代码
#include<fstream>
using namespace std;
ifstream cin("in.txt",ios::in);
ofstream cout("out1.txt",ios::out);
int main()
{
int a,b;
cin>>a>>b;
cout<<a+b;
return 0;
}
编译 连接 后生成一个 my.exe
2.AC代码
#include<fstream>
using namespace std;
ifstream cin("in.txt",ios::in);
ofstream cout("out2.txt",ios::out);
int add(int a,int b)
{
return a+b;
}
int main()
{
int a,b;
cin>>a>>b;
cout<<add(a,b);
return 0;
}
编译 连接 后生成一个 ac.exe
3.数据生成器
#include<fstream>
#include<cstdlib>
#include<ctime>
using namespace std;
ofstream cout("in.txt",ios::out);
int main()
{
cout<<rand()<<' '<<rand();
return 0;
}
编译 连接 后生成一个 data.exe
4.对拍模板
新建一个文件夹,把 my.exe , ac.exe , data.exe 放到里面
新建 对拍.txt 文本 (就是鼠标右键–>新建–>记事本)
然后在 对拍.txt 里面输入
@echo
:loop
data.exe
my.exe
ac.exe
fc out1.txt out2.txt
if not errorlevel 1 goto loop
pause
:end
然后,把后缀改为 .bat --> 对拍.bat 双击打开就可以开始对拍了
如果比较出现不同,就会暂停,然后输出到黑窗口中
p.s.
如果你像获取取错误的输入输出数据以及AC的数据,只需要打开你在程序中指定的输出输入文件即可。本例中,我们的输入文件为in.txt 输出文件为 out1.txt out2.txt。所以打开文件即可。