使用c-style i / o编程时,我有时会使用freopen()重新打开stdin进行测试,这样我就不必重复输入输入。我想知道是否有相当于c ++的i / o流。另外,我知道我可以使用管道在命令行/终端上重定向/无论如何但是我想知道是否有办法在我的代码中执行它(因为你可以看到,我不是很了解CL / T / W)。
答案 0 :(得分:30)
freopen
也适用于cin
和cout
。无需搜索新内容。
freopen("input.txt", "r", stdin); // redirects standard input
freopen("output.txt", "w", stdout); // redirects standard output
int x;
cin >> x; // reads from input.txt
cout << x << endl; // writes to output.txt
编辑:来自C ++标准27.3.1:
对象cin控制与对象stdin关联的流缓冲区的输入,在
<cstdio>
中声明。
因此,根据标准,如果我们重定向stdin
,它也会重定向cin
。反之亦然cout
。
答案 1 :(得分:15)
#include <iostream>
#include <fstream>
int main() {
// Read one line from stdin
std::string line;
std::getline(std::cin, line);
std::cout << line << "\n";
// Read a line from /etc/issue
std::ifstream issue("/etc/issue");
std::streambuf* issue_buf = issue.rdbuf();
std::streambuf* cin_buf = std::cin.rdbuf(issue_buf);
std::getline(std::cin, line);
std::cout << line << "\n";
// Restore sanity and read a line from stdin
std::cin.rdbuf(cin_buf);
std::getline(std::cin, line);
std::cout << line << "\n";
}
答案 2 :(得分:1)
This新闻组发布会探讨您的选择。
这取决于系统,海报没有注明 系统,但cin.clear()应该工作。我测试了附件 在具有AT&amp; T版本的iostream的UNIX系统上的程序。
#include <iostream.h>
int main()
{
for(;;) {
if ( cin.eof() ) {
cout << "EOF" << endl;
cin.clear();
}
char c ;
if ( cin.get(c) ) cout.put(c) ;
}
}
是的,这在cfront和TC ++中运行正常。 在g ++中,问题首先出现时需要采取额外的措施:
cin.clear();
rewind ( _iob ); // Seems quite out of place, doesn't it?
// cfront also accepts but doesn't
// require this rewind.
虽然我注意到这是在1991年,但它应该仍然有效。请务必使用现在标准的iostream
标头,而不是iostream.h
。
(顺便说一句,我发现用谷歌搜索词“重新打开cin c ++”的帖子,第二个结果。)
告诉我们您是如何继续前进的。您也可以使用freopen
。