問題描述
如何將 cin
重定向到 in.txt
并將 cout
重定向到 out.txt
?
How can I redirect cin
to in.txt
and cout
to out.txt
?
推薦答案
這是您想要執(zhí)行的操作的示例.閱讀注釋以了解代碼中每一行的作用.我已經(jīng)在我的電腦上用 gcc 4.6.1 測試過它;它工作正常.
Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.
#include <iostream>
#include <fstream>
#include <string>
void f()
{
std::string line;
while(std::getline(std::cin, line)) //input from the file in.txt
{
std::cout << line << "
"; //output to the file out.txt
}
}
int main()
{
std::ifstream in("in.txt");
std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
std::string word;
std::cin >> word; //input from the file in.txt
std::cout << word << " "; //output to the file out.txt
f(); //call function
std::cin.rdbuf(cinbuf); //reset to standard input again
std::cout.rdbuf(coutbuf); //reset to standard output again
std::cin >> word; //input from the standard input
std::cout << word; //output to the standard input
}
您可以在一行中保存和重定向:
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect
此處 std::cin.rdbuf(in.rdbuf())
將 std::cin's
緩沖區(qū)設(shè)置為 in.rdbuf()
然后返回與 std::cin
關(guān)聯(lián)的舊緩沖區(qū).使用 std::cout
也可以做到同樣的事情 —或任何流.
Here std::cin.rdbuf(in.rdbuf())
sets std::cin's
buffer to in.rdbuf()
and then returns the old buffer associated with std::cin
. The very same can be done with std::cout
— or any stream for that matter.
希望有所幫助.
這篇關(guān)于如何將cin和cout重定向到文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!