嗨,你們所有的你們精彩的程序員。 我一直在試圖使例如執行代碼std :: cout重定向的範圍
std::cout << "hello" << std::endl;
單詞「hello」將被寫入我重定向到文件時std::cout
重定向到一個文件。
我有followig程序:
// Redirection.cpp
#include <iostream>
#include <fstream>
int main(int argc, char **argv) {
if(argc == 2){
std::cout << "Output file supplied, redirecting to output.txt" << std::endl;
std::ofstream out("C:\\Avner\\HUJI\\CPP\\ex2\\output.txt");
std::cout.rdbuf(out.rdbuf());
std::cout << "This file contains output of Redirection.cpp" << std::endl;
}
std::cout << "This should be displayed in console or in the output file, if supplied" << std::endl;
return 0;
}
我期待output.txt
閱讀:
This file contains output of Redirection.cpp
This should be displayed in console or in the output file, if supplied
而是隻寫着:
This file contains output of Redirection.cpp
我的身影,重定向我使用僅適用於該範圍,而不適用於任何外部範圍。
我該如何解決這個問題?我需要的行爲是,只有在提供輸出文件時,所有打印纔會寫入該文件而不是控制檯。
非常感謝您的支持!
不,你的'out'對象超出了範圍.. – WhiZTiM
你真的需要額外的東西,'std :: endl'嗎? ''\ n''結束一行。 –
嗨皮特。我不這麼認爲,但這是他們在課堂上問我們的。謝謝! – avneraggy