繁体   English   中英

是否有 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM