scanf/printf vs cin/cout

As it is known that C scanf/printf works faster for Input/Output compared to cin/cout of C++.

I read in some blogs that adding the following

"std::ios_base::sync_with_stdio(false);" in a C++ code makes it run faster? Does it also increases the speed of Input/Output?
--------------------------------------------------------------------------------
So I tried to test this fact on the following problem:

http://www.codechef.com/problems/TSORT

Here are the two solutions to the problem:
1) Using std::cin/cout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
 	std::ios_base::sync_with_stdio(false);
int n; std::cin >>n; int a[n]; 
for(int i=0;i<n;i++)
std::cin >>a[i];
 
sort(a,a+n);
 
for(int i=0;i<n;i++)
std::cout<<a[i]<<endl;
 
return 0;
} 

--------------------------------------------------------------------------------
2. Using scanf/printf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
int n; scanf("%d",&n); int a[n]; 
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
 
sort(a,a+n);
 
for(int i=0;i<n;i++)
printf("%d\n",a[i]);
 
return 0;
}
  

-------------------------------------------------------------------------------

Surprisingly enough, the second code runs within time limit of 5 seconds while the first one gives Time limit exceeded.

Why is this happening? Please help me out.

Also, Please suggest some ways to fasten the input/output in C++. Thanks
Last edited on
Why is this happening? Please help me out.

You are flushing the ouput stream after every use.

Change line 14 to std::cout << a[i] << '\n'.
Wow, Thanks! It worked, Can you explain it in simple language why is it behaving that way? Or maybe any useful links where I can read about streams?

I'll be very greatful to you. Thanks
closed account (10X9216C)
Lol at the top solution for that problem.

http://www.cplusplus.com/reference/ostream/ostream/flush/
http://www.cplusplus.com/reference/ostream/endl/

std::endl causes flush to be called after it inserts the newline character.
@myesolar:
Yeah, just that I don't know C# lol, nor I feel like switching to it any time soon.

Thanks for the links.
Topic archived. No new replies allowed.