我正在使用以下命令执行我的程序:
./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
重定向 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]);
可能还有其他错误,但这是我发现的错误。
关于c++ - 如何重定向 cout 和 cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128478/