Как перенаправить cin в in.txt и cout в out.txt?
Как перенаправить cin и cout в файлы?
Ответ 1
Вот рабочий пример того, что вы хотите сделать. Прочитайте комментарии, чтобы узнать, что делает каждая строка в коде. Я тестировал его на своем компьютере с gcc 4.6.1; он отлично работает.
#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 << "\n";   //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 buffer в in.rdbuf(), а затем возвращает старый буфер, связанный с std::cin. То же самое можно сделать с помощью std::cout — или любой поток в этом отношении.
Надеюсь, что это поможет.
Ответ 2
Просто напишите
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}
		Ответ 3
Предполагая, что ваш компилятор prog name - x.exe и $- системная оболочка или приглашение
$ x <infile >outfile 
будет вводить данные из infile и выводится в outfile.
Ответ 4
Вот краткий фрагмент кода для затенения cin/cout, полезного для конкурсов программирования:
#include <bits/stdc++.h>
using namespace std;
int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");
    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}
Это дает дополнительное преимущество, поскольку простые потоки быстрее, чем синхронизированные потоки stdio. Но это работает только для области одиночной функции.
Глобальная переадресация cin/cout может быть записана как:
#include <bits/stdc++.h>
using namespace std;
void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}
int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");
    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);
    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());
    func();
}
Обратите внимание, что ios_base::sync_with_stdio также сбрасывает std::cin.rdbuf. Таким образом, порядок имеет значение.
См. также Значение ios_base:: sync_with_stdio (false); cin.tie(NULL);
Std io-потоки также могут быть легко затенены для области одного файла, что полезно для конкурентного программирования:
#include <bits/stdc++.h>
using std::endl;
std::ifstream cin("input.txt");
std::ofstream cout("output.txt");
int a, b;
void read() {
    cin >> a >> b;
}
void write() {
    cout << a + b << endl;
}
int main() {
    read();
    write();
}
Но в этом случае нам нужно поочередно выбирать объявления std и избегать using namespace std;, поскольку это приведет к ошибке двусмысленности:
error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^
См. также Как правильно использовать пространства имен в С++?, Почему используется "using namespace std" считаются плохой практикой? и Как разрешить конфликт имен между пространством имен С++ и глобальной функцией?