[英]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進行重定向。 我相信這也會使代碼更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.