C++从文件读取和输出的宏

Macro for C++ to read and output from files

所以我做竞技编程,经常需要用到文件,所以我一般是这样的:

ifstream fin ("fileName.in");
ofstream fout ("fileName.out");

但我想制作一个宏来在一行中执行此操作,如下所示:

#define file(name); {ifstream fin(#name".in"); ofstream fout(#name."out");}

有办法吗?

如果您经常使用该模式以至于想用它制作一个宏,您可能还会检查打开文件是否有效,所以我建议也将该检查添加到宏中。

展开的宏周围的大括号限制了变量的范围,因此您无法在展开宏后使用它们。可以像这样连接字符串文字:"this""is""a""string""thisisastring".

相同

所以,像这样的东西应该可以工作:

#include <fstream>

#define with_file(name) std::ifstream fin(name".in"); std::ofstream fout(name".out"); if(fin&&fout)

int main() {
    with_file("the_file") {
        // use fin and fout
    }
}