ios::sync_with_stdio(false);

· · 个人记录

ios::sync_with_stdio(false);

用来提速cin和cout

C++中,cin和cout要与stdio同步,中间会有一个缓冲,所以导致cin,cout语句输入输出缓慢,这时就可以用这个语句,取消cin,cout与stdio的同步, 效率基本与scanf和printf一致

但此时不能再使用scanf和printf

会出现玄学错误

eg:

#include<bits/stdc++.h>
using namespace std;
int main(){
    freopen("cg.out","w",stdout);
    ios::sync_with_stdio(false);
    printf("B\n");
    cout<<'A'<<endl;
    fclose(stdout);
}

output:

A

B

并且加入

ios::sync_with_stdio(false);

以后,如果写了fclose(stdout);

输出时最后一定要换行,否则就没有输出

另外,如果使用文件输入输出的话,一定记住要把这条语句放在freopen()后面


eg

#include<bits/stdc++.h>
using namespace std;
int main(){
    freopen("cg.out","w",stdout);
    ios::sync_with_stdio(false);
    cout<<'B'<<endl;
    cout<<'A';
    fclose(stdout);
}

output:

B