如何重定向cout和cin
How to redirect cout and cin?
我正在用以下命令执行程序:./myProgram -i test.in -o test.out
两个文件都是合法存在的。
// run all over the arguments and set the cin and cout if needed
for (int i = 1; i < argc; i= i+2)
{
int j = i+1;
// loop over each pairs of arguments
do
{
// set cin
if(argv[i] == "-i")
{
static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
break;
}
//set cout
if(argv[i] == "-o")
{
std::ofstream out(argv[j]);
std::cout.rdbuf(out.rdbuf());
break;
}
// in order to search for the other case
// (example:X.out -i)
int temp = i;
i = j;
j = temp;
}while(i>j);
}
我在main
中写了这个块,以便根据char **argv
重定向cin
和cout
。cin
工作很好,但cout
没有。当我这样做时,它可以工作:
// run all over the arguments and set the cin and cout if needed
for (int i = 1; i < argc; i= i+2)
{
int j = i+1;
// loop over each pairs of arguments
do
{
// set cin
if(argv[i] == "-i")
{
static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
break;
}
//set cout
if(argv[i] == "-o")
break;
// in order to search for the other case
// (example:X.out -i)
int temp = i;
i = j;
j = temp;
}while(i>j);
}
std::ofstream out(argv[4]);
std::cout.rdbuf(out.rdbuf());
是什么导致了这个问题?
安装到std::cout
的流缓冲区的流将在安装流缓冲区后立即被销毁:
std::ofstream out(argv[j]);
std::cout.rdbuf(out.rdbuf());
第一行需要读成
static std::ofstream out(argv[j]);
可能还有其他错误,但这是我发现的。
它不起作用,因为需要将j设置为i+1
才能使输出重定向工作。试一试——如果你先通过-o
,然后在第一个样本中通过-i
,会发生什么?
改变:
int temp = i;
i = j;
j = temp;
:
int temp = i;
i = j;
j = temp + 1;
您还必须处理while条件。
顺便问一下,你为什么需要j
?您只能使用i,然后使用i+1进行重定向。我相信这也会使代码更容易理解。
相关文章:
- 为什么 printf 在 C++ 中的执行速度比 cout 快?另外scanf比cin慢,为什么?
- 使用 CIN COUT 显示垃圾值的文件对象?
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 两个 cin / cout 语句合并为一个
- 防止 cin、cout、cerr 被实例化
- 无法让我了解 cin.get 和 cout 在这里的工作方式
- 使用 std::endl 与 "n" 当 cin 和 cout 被解绑时
- CIN 和 COUT 如何在以下程序中工作
- 使用自定义宏来简化 cin 和 cout 语句等内容被认为是更好还是更差
- 简单的cin cout代码由"build and run"运行,但从bin/debug/x开始工作.exe
- 通过 cin/cout 的协议单元测试 - 如何阻止流以等待内容?
- 为什么 CIN / COUT 比 scanf/printf 慢
- 从printf-scanf转换为cin-cout时出现问题
- cin/cout 使用什么技术/模式允许例如 cout << x << y
- 为什么我不能将 cin/cout 放在一个函数中并从 main() 调用该函数
- 交替使用cin/cout很慢
- 关于 cin/cout 过载的简单问题 4.
- cin / cout being skipped
- c++, cin, cout, threads和sync_with_stdio的输出损坏