cin\cout太慢导致超时,sync_with_stdio与cin.tie的完美运用

大概讲一下经过,之前用cin超时,用scanf过了,然后找加快cin速度的方法。

看到很多人,网上说只要加上一下代码就好了。

 1 std::ios::sync_with_stdio(false); 

个人试过之后不行。网上盲目转载的人,我真心鄙视。

我找了很久,发现其实要两个命令一起用。

ios::sync_with_stdio(false);
cin.tie(0);   

如果没有使用using namespace std;语句,就要变成

std::ios::sync_with_stdio(false);
std::cin.tie(0);

这两个命令放在main()的开头就好了,以下是简单示例

 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 #include <iomanip>
 5 using namespace std;
 6 
 7 int main(){
 8     std::ios::sync_with_stdio(false);
 9     std::cin.tie(0);
10     string s;
11     int a;
12     cout<<" input s: "<<endl;
13     cin>>s;
14     cout<<endl<<s<<endl<<endl;
15     cout<<" input a: "<<endl;
16     cin>>a;
17     cout<<endl<<setbase(16)<<setw(6)<<setfill('*')<<a<<endl;;
18     
19     return 0;
20 }
 input s:
abcde

abcde

 input a:
45

****2d

--------------------------------
Process exited after 6.359 seconds with return value 0
请按任意键继续. . .

当然使用这些命令会有个问题,就是不能再用scanf了(不过好像也不需要了)

可以看见,程序成功接收了字符串和int。而且iomapip还是可以使用的

猜你喜欢

转载自www.cnblogs.com/VsKendo/p/9360908.html