문제
코드를 컴파일하려고 할 때
istream in;
if (argc==1)
in=cin;
else
{
ifstream ifn(argv[1]);
in=ifn;
}
GCC가 실패하여 불평합니다 operator=
비공개입니다. 설정할 수있는 방법이 있습니까? istream
조건에 따라 다른 값으로?
해결책
CIN의 StreamBuf를 다른 것으로 대체 할 수 있으며 일부 프로그램에서는 CIN을 직접 언급하지 않고 Istreams를 통과하는 일반적인 전략보다 간단합니다.
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;
}
Contor Control Leave Main 후 CIN을 사용하는 것은 매우 드물지만, 위의 시도 캐치는 프로그램이 할 수있는 일이라면 정의되지 않은 행동을 피합니다.
다른 팁
포인터를 사용할 수 있습니다 in
, EG :
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