5 ответов:
вот рабочий пример того, что вы хотите сделать. Прочитайте комментарии, чтобы узнать, что делает каждая строка в коде. Я протестировал его на своем ПК с 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буферin.rdbuf()и затем возвращает старый буфер, связанный сstd::cin. То же самое можно сделать и сstd::cout- либо поток для этот вопрос.надеюсь, что это поможет.
просто писать
#include <cstdio> #include <iostream> using namespace std; int main() { freopen("output.txt","w",stdout); cout<<"write in file"; return 0; }
предполагая, что ваше имя компиляции prog x.exe и $ - это системная оболочка или подсказка
$ x <infile >outfileбудет принимать входные данные из файла и выводить в выходной файл .
вот короткий фрагмент кода для затенения 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; }это дает дополнительное преимущество, что простые fstreams быстрее, чем синхронизированные потоки 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 также могут быть легко затенены для области одного файла, что полезно для конкурентного программирования:
#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 ^см. также Как правильно использовать пространства имен в C++?,почему " использование пространства имен std" считается плохой практикой? и как разрешить конфликт имен между пространством имен C++ и глобальной функцией?
попробуйте перенаправить cout в файл.
#include <iostream> #include <fstream> int main() { /** backup cout buffer and redirect to out.txt **/ std::ofstream out("out.txt"); auto *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(out.rdbuf()); std::cout << "This will be redirected to file out.txt" << std::endl; /** reset cout buffer **/ std::cout.rdbuf(coutbuf); std::cout << "This will be printed on console" << std::endl; return 0; }Читать статью полностью используйте std::rdbuf для перенаправления cin и cout
Comments