新手C++程序员在这里。我试图编写一个命令行应用程序,它接受两个参数,一个输入文件和一个输出文件。但是,如果输入文件或输出文件名称是“ - ”,则需要程序读取/输出到标准输入/输出。我的问题是,在C++中,如果编译器不知道输入/输出流是否已初始化,我不知道该如何做到这一点。这是我的代码。有条件地从标准输入或文件读取文件
if(argv[1] == "-") {
istream input;
cout << "Using standard input" << endl;
}
else {
ifstream input;
cout << "Using input file " << argv[1] << endl;
input.open(argv[1], ios::in);
if(!input) {
cerr << "Cannot open input file '" << argv[1]
<< "', it either does not exist or is not readable." << endl;
return 0;
}
}
if(argv[2] == "-") {
ostream output;
cout << "Using standard output" << endl;
}
else {
ofstream output;
cout << "Using output file " << argv[2] << endl;
output.open(argv[2], ios::out);
if(!output) {
cerr << "Cannot open output file '" << argv[2] << "' for writing."
<< " Is it read only?" << endl;
return 0;
}
}
在这里,我不能调用操作>>输入,因为,我猜,编译器不知道它已经初始化。
我发布了一些有关[最近](http://stackoverflow.com/a/9244559/596781)的效果。 – 2012-02-12 17:42:35
'argv [1] ==“ - ”'不会做你认为它做的事情。你正在使用哪一本C++书? – 2012-02-12 17:54:47
我一直在使用Bruce Eckel的“Thinking in C++”,但我的大多数坏习惯都来自我的Java编程经验。 – Stegosaurus 2012-02-12 18:11:32