質問
コードをコンパイルしようとするとき
istream in;
if (argc==1)
in=cin;
else
{
ifstream ifn(argv[1]);
in=ifn;
}
GCCは失敗し、不平を言っています operator=
プライベートです。設定する方法はありますか istream
状態に基づいて異なる値に?
解決
CinのStreambufを別のものに置き換えることができます。一部のプログラムでは、CINを直接参照せずにISTREAMを渡すという一般的な戦略よりも簡単です。
int main(int argc, char* argv[]) {
ifstream input;
streambuf* orig_cin = 0;
if (argc >= 2) {
input.open(argv[1]);
if (!input) return 1;
orig_cin = cin.rdbuf(input.rdbuf());
cin.tie(0); // tied to cout by default
}
try {
// normal program using cin
}
catch (...) {
if (orig_cin) cin.rdbuf(orig_cin);
throw;
}
return 0;
}
コントロールがメインを去った後にCINを使用することは非常にまれですが、上記のトライキャッチは、それがあなたのプログラムがするかもしれない場合、未定義の動作を避けます。
他のヒント
ポインターを使用できます in
, 、例:
istream *in;
ifstream ifn;
if (argc==1) {
in=&cin;
} else {
ifn.open(argv[1]);
in=&ifn;
}
それで、「適切なコンストラクターが利用できない」と不平を言っていませんか?とにかく、以下のように変更できます。
void Read(istream& is)
{
string line;
while (getline(is, line))
cout << line;
}
int main(int argc, char* argv[])
{
if (argc == 1)
Read(cin);
else
{
ifstream in("sample.txt");
Read(in);
}
}
このようなストリームに影響を与えることはできません。ただし、達成したいことは、iStreamへのポインターを使用して取得できます。
#include <fstream>
#include <istream>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
istream *in;
// Must be declared here for scope reasons
ifstream ifn;
// No argument, use cin
if (argc == 1) in = &cin;
// Argument given, open the file and use it
else {
ifn.open(argv[1]);
in = &ifn;
}
return 0;
// You can now use 'in'
// ...
}
所属していません StackOverflow