How can I do file i/o without fstream for competitions like google code jam?
Let me preface this question by saying I am not a very experienced programmer.
For competitions like google code jam, I write code like this:
#include <fstream>
using namespace std;
int main() {
ifstream fin("file.in");
ofstream oin("file.out");
//Etc. I'll now write out my solution.
//...
}
However, I noticed that many other code sources by other participants don't use fstream at all and use iostream instead. Then they'll use cout and cin as if they were reading and writing from the console.
How are they doing this? Can I do the same thing if I am using g++ and ubuntu?
EDIT: Since it was requested that I post an example of what I mean, here is code from participant ryuuga who solved large Bot Trust, Problem A from the recent '11 qualification round.
He uses cin and cout but I don't know how he is doing file i/o.
#include <iostream>
using namespace std;
#include <cstdio>
#include <algorithm>
#include <deque>
#include <map>
#include <set>
typedef pair<int,int> pii;
#include <vector>
typedef vector<int> vi;
#include <queue>
#include <stack>
#define For(i,a,b) for(int i=(a);i<(b);++i)
#define ForI(i,a,b) for(int i=(a);i<=(b);++i)
#define ForAll(it,set) for(typeof(set.begin()) it = set.begin(); it!=set.end(); ++it)
typedef stack<int> si;
typedef queue<int> qi;
int main(){
int t;
cin>>t;
ForI(tt,1,t){
int n;cin>>n;
int pos[2]={1,1}, time[2] = {0,0};
int curTime = 0;
For(i,0,n){
char type; int button;
cin>>type>>button;
type = (type=='B'?1:0);
int nextTime = 1+max(curTime, time[type] + abs(button - pos[type]));
pos[type] = button;
time[type] = nextTime;
curTime = nextTime;
}
cout<<"Case #开发者_运维问答"<<tt<<": "<<curTime<<endl;
}
return 0;
}
Imagine when you are using the shell in ubuntu. Almost everything is read by the console, cin and written to the console, cout. For instance
cat "file.txt" | grep "Hello"
cat would get the "file.txt" from the arguments given to main, i.e.
main(int argc, char ** argv){
// for the both cat and grep examples argc is 2
// argv[1] contains "file.txt" for cat.
// open an ifstream and ouput it to cout. There's cat for you.
}
To find out what argv[0]
contains, try it out!
grep
would read the same argument then read everything from cin, copy the input that matches argv[1]
to cout
EDIT: He is running his program with
cat "downloaded-input-file.txt" | theprogram > output.txt
Then submits the program. Or he might be using the < downloaded-input-file
syntax. I'm keeping the initial explanation as it might be useful for the understanding of the process.
精彩评论