3 solutions
-
4
/**第一种,使用freopen重定向函数将标准输入输出重定向到文件,无需改变scanf、printf、cin和cout(头文件为stdio.h或cstdio) 函数原型:FILE *freopen(const char *_FileName,const char *_Mode,FILE *_Stream) 在FileName中输入目标文件,Mode输入模式("r"为只读模式,"w"为写入模式),Stream中输入需要重定向的原始方式 (通常为标准输入/输出/错误流(stdin/stdout/stderr)) */ /*#include <cstdio> using namespace std; int a, b; int main() { freopen("a+b.in", "r", stdin);//将标准输入重定向到a+b.in文件中 freopen("a+b.out", "w", stdout);//将标准输出重定向到a+b.out文件中 scanf("%d%d", &a, &b); printf("%d", a + b); fclose(stdin); fclose(stdout);//关闭文件,可省略 return 0; }*/ /** 第二种,使用fopen函数与FILE指针,fscanf和fprintf读取和写入文件(头文件为stdio.h或cstdio) fopen函数原型:FILE *fopen(const char *_FileName,const char *_Mode) 在FileName中输入目标文件,Mode输入模式("rb"为只读模式,"wb"为写入模式),赋值给两个文件指针 fscanf,fprintf第一个参数为目标文件指针,后面两个与scanf,printf一样 */ /*#include <cstdio> using namespace std; FILE *fin,*fout;//定义文件指针 int a, b; int main() { fin = fopen("a+b.in", "rb");//将输入指针定向到a+b.in文件中 fout = fopen("a+b.out", "wb");//将输出指针定向到a+b.out文件中 fscanf(fin,"%d%d", &a, &b);//从fin读入数据 fprintf(fout,"%d", a + b);//数据输出到fout fclose(fin); fclose(fout);//关闭文件,可省略 return 0; }*/ /** 第三种,使用stream流读取与输入(头文件为fstream) 首先,定义ifstream,ofstream变量并输入文件名 格式:ifstream 变量名("输入文件名") ofstream 变量名("输出文件名") 之后的读写部分和cin,cout格式相同,只需把cin,cout替换为对应的变量名即可 */ /*#include<fstream> using namespace std; ifstream fin("a+b.in"); ofstream fout("a+b.out"); int a,b; int main() { fin >> a >> b;//通过fin流输入数据 fout << a+b;//通过fout流输出数据 fin.close(); fout.close();//关闭文件,可省略 return 0; }*/
- 1
Information
- ID
- 1066
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 5
- Tags
- (None)
- # Submissions
- 90
- Accepted
- 33
- Uploaded By