-1

I have written a simple code in C++. But suddenly i got one weird behavior by the output of my code. I am not getting why i am getting this type of problem here.

Below is My Simple C++ Code :

#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cout<<"Hi\n";
    lli a[] = {1,2,3,4,5,6,7};

    cout<<"Original Array : ";
    for(int i=0;i<7;i++)
    cout<<a[i]<<" ";

    lli q;
    cout<<"\n\nEnter q : ";
    cin>>q;

    cout<<"q = "<<q<<"\n";
}

The weird behavior is this : Whenever i am running my code. It is not printing any output message "Hi..and all". It seems it is directly asking for the input of used "q" variable ( below ) first. Then it is printing the required output. I am very much confused by this behavior. Please tell me why my code is asking for the input of q first. And then it is showing original behavior.

Below is the output of my code :

enter image description here

Note : Whenever i am removing these three lines :

ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);

It is behaving perfectly as required. I am not getting Why.

SAPJV
  • 115
  • 8

2 Answers2

4

The cause is cin.tie(NULL);. It means that you de-synchronize console input with output. This means that console output appears as late as possible (when the program ends). Normally the output buffer is flushed (displayed) whenever there is an input operation pending, however by using cin.tie(NULL); you explicitly say that you don't want this to happen.

3

C++ output streams are buffered. When you write to std::cout, the data is stored in memory, and will only be passed to the output device when the buffer fills up or the stream is explicitly flushed. The output you send to std::cout won't appear on the screen until one of those conditions occurs. This is done to improve performance, since I/O operations are very slow compared to writing to memory.

By default, std::cout is tied to std::cin as if std::cin.tie(&std::cout) had been called. This means that before std::cin does any read operation, it will automatically call std::cout.flush(). This is a useful default, since it ensures that any prompt you wrote to std::cout will appear before std::cin blocks waiting for input. By calling std::cin.tie(NULL), you have explicitly opted to turn off this feature, so it's up to you to ensure you call std::cout.flush() explicitly before you read from std::cin to ensure the buffered data has been written to the terminal.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52