cout.put(ch)

OS: mac osx 10.9 xcode 4.6.3

i don't understand why i need to flush my console output, cout.flush(), in order to make the content of the file visible in the console window.

cout.flush() is a solution to my problem, but i don't understand why i need it and can't do without.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ShowFileContents.cpp
// --------------------
// This program displays the contents of a file chosen by the user

#include <iostream>
#include <fstream>
#include <string>
#include "console.h" //creates a console window on the screen
#include "filelib.h" //implements the function promptUserForFile
using namespace std;

// main program
int main() {
    ifstream infile;
    promptUserForFile(infile, "Input file: ");
    char ch;
    while (infile.get(ch)) {
        cout.put(ch);
    }
    cout.flush(); //why do i need this line?
    infile.close();
    return 0;
}
console interaction in modern OS usually done through several layers of abstraction. Because of that it is slow. To combat it programs usually uses buffering: they store output in internal character buffer and outputs it to the console in chunks. Output happens: before console input, when buffer is full or when you explicitely say so by std::cout.flush() or std::cout << std::flush (std::endl is quivalent of << '\n' << std::flush)
closed account (jvqpDjzh)
What exactly is this internal character buffer? Is there a way to know the size of this internal character buffer?
Last edited on
It is implementation defined. It does not even need to be consistent between two program launches or even between two put() calls. You should check your compiler documentation or cout implementation in it.

You can also look at http://en.cppreference.com/w/cpp/io/manip/unitbuf
This shows how to make output unbuffered (can cause 10-15 times slowdown)
But in any case, shouldn't std::cout be getting automatically flushed at the end before the program terminates (and also before any input operation using std::cin)?

Or is it possible/allowed for this program:
1
2
3
4
5
6
#include <iostream>

int main()
{
    std::cout << "Hello world!":
}
...to produce no output?
It should flush stream before terminating program. Maybe console window is closing before you could read the output?

I did not work with xcode, but there is some hint which might help you:
in Xcode click run then Console. Your output is there.
Topic archived. No new replies allowed.