为什么我需要在main里面写std::ios::sync_with_stdio

Why do I need to write std::ios::sync_with_stdio inside main?

本文关键字:stdio std ios sync with main 为什么      更新时间:2023-10-16

如果我写:

#include <iostream>
using namespace std;
main(){
    ios::sync_with_stdio(false);
    cout << "hi";
}

然后,程序编译正确,但是如果我写:

#include <iostream>
using namespace std;
ios::sync_with_stdio(false);
main(){
    cout << "hi";
}

则GCC产生以下错误:

错误:特化成员'std::basic_ios::sync_with_stdio'需要'template<>'语法ios: sync_with_stdio(假);

这个错误意味着什么,以及如何纠正它(如果可能的话)?

如果在main()之外写ios::sync_with_stdio(false)行,编译器会将其解释为函数声明。然后它抱怨缺少template<>

要调用这个函数,你需要这样写:

bool result = std::ios::sync_with_stdio(true);

要重新定义静态函数,需要这样写:
bool std::ios_base::sync_with_stdio(bool sync)
{
  //do something
  return true;
}

更正为

std::ios_base::sync_with_stdio(false);

或者对于像cin这样的特定流,您可以

cin.sync_with_stdio(false);

它应该在函数内部,因为它是一个表达式而不是一个语句。