HitmanBBa's blog

By HitmanBBa, 9 years ago, In English

Hello everyone.

Today, while I'm trying to solve this easy problem 404A - Valera and X,

I write this code 11264735 using cin.tie(0); and ios_base::sync_with_stdio(0); and I got a wrong answer on test 2, but when I removed them from my code 11264741 I got Accepted, why??

Tags c++
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it +5 Vote: I do not like it

You can't use printf/scanf once you write ios_base::sync_with_stdio(0)

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you explain, please :)

    • »
      »
      »
      9 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      ios_base::sync_with_stdio(0) will de-synchronize cin from scanf and cout from printf. This is fine and will result in a speedup if you just use cin and cout, but if you mix that with stdio-style IO, then weird things happen. For example if the input is 5 6 and your code says

      int a, b;
      scanf("%d", &a);
      cin >> b;
      

      You might get a=6, b=5 or something like that. Similarly,

      printf("%s", "YES");
      cout << "NO";
      

      might result in "NOYES" instead of "YESNO". At least that's my understanding of it.

      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Thanks a lot. :)

      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        what is the use of cin.tie(0) ?

        • »
          »
          »
          »
          »
          9 years ago, # ^ |
            Vote: I like it +1 Vote: I do not like it

          It seems that by default, cout is flushed before each input operation on cin:

          http://www.cplusplus.com/reference/ios/ios/tie/

          cin.tie(0) turns this off by instead "tying" cin to nothing.

          Presumably this is done for performance reasons. It would make a significant difference in programs that interweave numerous cin/cout calls, such as those that answer a large number of queries from the input in an online manner.