如何将cin
重定向到in.txt
,将cout
重定向到out.txt
发布于 2012-12-15 08:46:59
只需写
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
freopen("output.txt","w",stdout);
cout<<"write in file";
return 0;
}
发布于 2016-07-21 20:56:01
下面是一个简短的代码片段,用于跟踪cin/cout,这对编程竞赛很有用:
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream cin("input.txt");
ofstream cout("output.txt");
int a, b;
cin >> a >> b;
cout << a + b << endl;
}
这提供了额外的好处,即普通fstream比同步的stdio流更快。但这只适用于单个函数的范围。
全局cin/cout重定向可以写为:
#include <bits/stdc++.h>
using namespace std;
void func() {
int a, b;
std::cin >> a >> b;
std::cout << a + b << endl;
}
int main() {
ifstream cin("input.txt");
ofstream cout("output.txt");
// optional performance optimizations
ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cin.rdbuf(cin.rdbuf());
std::cout.rdbuf(cout.rdbuf());
func();
}
请注意,ios_base::sync_with_stdio
还会重置std::cin.rdbuf
。所以顺序很重要。
另请参阅Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);
Std io流也可以很容易地在单个文件范围内进行隐藏,这对于竞争性编程很有用:
#include <bits/stdc++.h>
using std::endl;
std::ifstream cin("input.txt");
std::ofstream cout("output.txt");
int a, b;
void read() {
cin >> a >> b;
}
void write() {
cout << a + b << endl;
}
int main() {
read();
write();
}
但在这种情况下,我们必须一个接一个地选择std
声明,并避免使用using namespace std;
,因为它会产生歧义错误:
error: reference to 'cin' is ambiguous
cin >> a >> b;
^
note: candidates are:
std::ifstream cin
ifstream cin("input.txt");
^
In file test.cpp
std::istream std::cin
extern istream cin; /// Linked to standard input
^
另请参阅How do you properly use namespaces in C++?、Why is "using namespace std" considered bad practice?和How to resolve a name collision between a C++ namespace and a global function?
发布于 2014-09-22 04:33:58
假设编译程序名称是x.exe,$是系统外壳或提示符
$ x <infile >outfile
将从infile获取输入,并将输出到outfile。
https://stackoverflow.com/questions/10150468
复制相似问题