답변:
수행하려는 작업의 실제 예는 다음과 같습니다. 주석을 읽고 코드의 각 줄이 무엇을하는지 알 수 있습니다. gcc 4.6.1로 내 PC에서 테스트했습니다. 잘 작동합니다.
#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'sin.rdbuf()std::cinstd::cout
희망이 도움이됩니다.
in과 out에서 쓸 수 읽기, in.txt그리고 out.txt각각. 또한, 파일이 때 자동으로 종료됩니다 in및 out범위 밖으로 이동합니다.
그냥 써
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
freopen("output.txt","w",stdout);
cout<<"write in file";
return 0;
}
stdout아니라 리디렉션 중 cout입니다.
std::sync_with_studio(false);기본 설정은로 설정되어 있지만 설정하지 않은 경우 true.
ofstream out("out.txt"); cout.rdbuf(out.rdbuf());한 줄만 추가 가능하며 이식 가능합니다. 너무 간단하지 않습니다 :)
다음은 콘테스트 프로그래밍에 유용한 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;
}
이는 일반 fstream이 동기화 된 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
^
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 리디렉션