下面是两段代码。一个有效,一个无效,我想知道为什么。对于缺少评论和糟糕的变量名,我提前道歉,但现在这种语言真的让我很吃力。
// File1.cpp (contains relevant includes)
// Works! It writes to out.txt and appears to use in.txt correctly
int main(int argc, char* argv[]) {
int num;
std::ifstream in("in.txt");
std::streambuf* cinbuf = std::cin.rdbuf();
std::cin.rdbuf(in.rdbuf());
std::ofstream out("out.txt");
std::streambuf* coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
cout << "Give me a number: ";
cin >> num;
std::cin.rdbuf(cinbuf);
std::cout.rdbuf(coutbuf);
return 0;
}
// File2.cpp (contains relevant includes)
// Does not work! Outputs nothing to out.txt.
class TestWithStdIO {
std::streambuf* cinbuf;
std::streambuf* coutbuf;
public:
TestWithStdIO(const char* inFile, const char* outFile) {
std::ifstream in(inFile);
cinbuf = std::cin.rdbuf();
std::cin.rdbuf(in.rdbuf());
std::ofstream out(outFile);
coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
}
~TestWithStdIO() {
std::cin.rdbuf(cinbuf);
std::cout.rdbuf(coutbuf);
}
};
int main(int argc, char* argv[]) {
int num;
TestWithStdIO* ioTest = new TestWithStdIO("in.txt", "out.txt");
cout << "Give me a number: ";
cin >> num;
delete ioTest;
return 0;
}