簡體   English   中英

cout可以與監視器以外的其他任何東西關聯嗎?

[英]Can cout be associated with anything other than monitor?

“ cout是一個輸出流對象,它附加到流程的標准輸出設備上,通常附加到運行程序的終端上”,我的書如此說道。

是否存在將cout連接到任何其他輸出設備(例如打印機)的情況?或者就像cout始終將監視器和cin稱為鍵盤一樣。

cin是標准輸入,盡管大多數系統都從鍵盤獲取輸入,但這不是必需的。 cout是標准輸出,大多數系統再次將stdout(標准輸出)設置為控制台。 但是您可以重定向它。

例如要歸檔:

  std::ofstream file;
  file.open ("test.txt"); // open file

  std::streambuf *orig_out = std::cout.rdbuf();     // save cout 
  std::streambuf *buf = file.rdbuf();   // get file's streambuf
  std::cout.rdbuf(buf);         // redirect cout to file
  std::cout << "This is written to the file";
  std::cout.rdbuf(orig_out);        // restore cout's original output

  file.close(); // close file

簡短的回答是“是”。 Cout只是一個輸出流。 在Unix中,您可以創建管道

command1 | command2

命令1的標准輸出轉到命令2的標准輸入-即不是顯示器和鍵盤。

stdout(和cout)也可以重定向:

command > some_file_or_device.

是。

cin和cout是iostream,它們是標准的,但它們也是正常的,即,您可以關閉stdin和stdout並重新打開其他設備作為stdin或out。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM