jay*_*jay 0 c++ file-io iostream
让我先说我不是一个非常有经验的程序员来回答这个问题。
对于像 google code jam 这样的比赛,我编写的代码如下:
#include <fstream>
using namespace std;
int main() {
    ifstream fin("file.in");
    ofstream oin("file.out");
    //Etc. I'll now write out my solution.
    //...
}
但是,我注意到其他参与者的许多其他代码源根本不使用 fstream,而是使用 iostream。然后他们将使用 cout 和 cin,就像从控制台读写一样。
他们是怎么做的?如果我使用 g++ 和 ubuntu,我可以做同样的事情吗?
编辑:由于有人要求我发布一个示例来说明我的意思,这里是参与者 ryuuga 的代码,他解决了最近 '11 资格赛中的大型机器人信任问题 A。
他使用 cin 和 cout 但我不知道他是如何进行文件 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;
}
想象一下当你在 ubuntu 中使用 shell 时。几乎所有内容都由控制台 cin 读取并写入控制台 cout。例如
cat "file.txt" | grep "Hello"
cat 将从给定 main 的参数中获取“file.txt”,即
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.
}
要了解argv[0]其中包含什么,请尝试一下!
grep会读取相同的参数,然后从 cin 读取所有内容,将匹配的输入复制argv[1]到 cout
编辑:他正在运行他的程序
cat "downloaded-input-file.txt" | theprogram > output.txt
然后提交程序。或者他可能正在使用< downloaded-input-file语法。我保留最初的解释,因为它可能有助于理解该过程。