如何重定向cout和cin

How to redirect cout and cin?

本文关键字:cin cout 重定向      更新时间:2023-10-16

我正在用以下命令执行程序:./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重定向cincoutcin工作很好,但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进行重定向。我相信这也会使代码更容易理解。