简体   繁体   中英

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

#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.

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.

If only iostreams are used you can add a manual flush to the output :

std::cout.flush();

Or

std::cout << /* the output */<< std::flush;

Also:

std::cout << std::endl is equivalent to std::cout << '\\n' << std::flush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM