c++ - 如何重定向 cout 和 cin?

标签 c++ cout 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 中写了这个 block ,以便根据 char **argv 重定向 cincout . 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]);

可能还有其他错误,但这是我发现的错误。

关于c++ - 如何重定向 cout 和 cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128478/

相关文章:

c++ - 查询性能计数器状态?

c++ - 使变量只读,但仍可由 C++ 中的客户端访问?

c++ - cout一个类的函数

c++ - 防止在我的行 C++ 的末尾打印额外的空格

c++ - 错误 : cout was not declared and is giving me compiling problems

c++ - 在 C++ 中添加类?

c++ - 为什么我的 unique_ptr 认为它有一个空函数指针删除器?

c++ - 为什么每个类不都有一个虚拟 ptr 呢?

c++ - 将多个字符串作为一个字符串读取? C++

C++ cout cin 字符串操作