我是一名新手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;
}
}
从这里开始,我无法在输入上调用运算符 >>,因为,我猜测,编译器不知道它是否被初始化。