Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When i use cout.tie(NULL), program doesn't print anything for my code, but if i print endl, program works fine

Tags:

c++

#include <bits/stdc++.h>

using namespace std;

void scan_a_line_indefinitely()
{
    // scan line indefinitely
    string input_line;
    while(getline(cin,input_line)) 
    {
        cout << input_line ; **// doesn't print if i use this line**
        //cout << input_line << endl; **// if i use this line, it works fine**
    }

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    scan_a_line_indefinitely();
    return 0;
}

someone please help me understand the problem with this code. i think the problem is with cout.tie() and cout.tie(), when i remove these, program works fine.

like image 719
Aakash Preetam Avatar asked Oct 17 '25 06:10

Aakash Preetam


1 Answers

std::cout will flush under these conditions:

  1. An input-stream which is tied to std::cout tries to read input.
    You removed the ties.

  2. iostreams are synchronized with stdio, thus effectively unbuffered.
    You disabled the synchronization.

  3. The buffer is full.
    That takes a bit longer.

  4. The program ends normally.
    That comes too late for you.

  5. There is a manual flush (stream.flush() which is called when streaming std::flush; stream << std::endl is equivalent to stream << stream.widen('\n') << std::flush).
    You have none of those.

So, fix any of them and you will see your output earlier.

like image 112
Deduplicator Avatar answered Oct 18 '25 20:10

Deduplicator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!