// 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
usingnamespace 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)
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.
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!":
}