是否有 ifstream 和 ofstream 的宏或缩短 ifstream/ofstream 的方法?

Is there a macro for ifstream and ofstream or a way to shorten ifstream/ofstream?

例如,如果我的文件名是:sum00.in,sum.00.out,是否有可能除了每次写相同的代码:

ifstream in("sum00.in");
ofstream out("sum00.out"); 

我首先想到的是宏:

#define read(x) ifstream in("x.in"); ofstream out("x.out"); ///But it doesn`t work for a word.

每条能帮助我写出同一篇文章的建议都会很有帮助!

我建议不要使用宏。我会将其封装在 class.

示例:

#include <fstream>
#include <iostream>
#include <string>

class MyIO {
public:
    explicit MyIO(const std::string& basename) :
        in(basename + ".in"),
        out(basename + ".out")
    {}
    std::ifstream& is() { return in; }
    std::ofstream& os() { return out; }

private:
    std::ifstream in;
    std::ofstream out;
};

int main() {
    MyIO f("sum001");      // open both sum001.in and sum001.out
    int i;
    int sum = 0;
    while(f.is() >> i) {   // read from the ifstream
        sum += i;
    }
    f.os() << sum << '\n'; // write to the ofstream
}