【发布时间】:2016-07-19 09:46:10
【问题描述】:
我想编写一个简单的程序,根据传递给它的选项,可执行文件会将输出打印到屏幕或文件中。程序很简单。
#include<iostream>
int main(int argc, char* argv[]){
... process options...
std::ostream& out = ... // maybe std::cout, maybe a *new* std::ofstream;
out << "content\n";
}
是否有一个好的习惯用法可以在运行时引用 std::cout 或文件流?
我尝试过使用指针,但它太可怕了。我无法避免使用指针(更不用说以后需要更丑陋的代码来删除指针)。
#include<iostream>
#include<ofstream>
int main(int argc, char* argv[]){
std::string file = argc>1?argv[1]:"";
std::clog << "file: " << file << '\n';
// if there is no argument it will print to screen
std::ostream* out = (file=="")?&std::cout:(new std::ofstream(file)); // horrible code
*out << "content" << std::endl;
if(out != &std::cout) delete out;
}
我不知道,也许 C++ 流的某些特性允许这样做。也许我必须使用某种类型的擦除。我认为,问题在于std::cout 是已经 存在的东西(是全球性的),但std::ofstream 是必须创建的东西。
我设法使用open 并避免使用指针,但它仍然很难看:
int main(int argc, char* argv[]){
std::string file = argc>1?argv[1]:"";
std::clog << "file: " << file << '\n';
std::ofstream ofs;
if(file != "") ofs.open(file);
std::ostream& out = (file=="")?std::cout:ofs;
out << "content" << std::endl;
}
【问题讨论】:
-
指针并不一定意味着动态分配。
-
可能有点不对劲,但如果是命令行程序,应该一直输出到
std::cout,让用户决定是否要将输出重定向到文件中。 -
这个问题可能很有趣:stackoverflow.com/questions/24706480/…