-3
int main(int argc, char *argV[]){

istream *br;
ifstream inFile;
if(argc == 2){

    inFile.open(argV[1]);

    if(inFile.is_open()){
        cout << "file opened."; //if only "file opened" has an "\n then only it will print 
        br = &inFile;     //and the program will freeze right after printing it
    }   
}
else if(argc <= 1){

    br = &cin;

}
else{

    cout << "Unrecognized commands";

}
cout << "test"; //having \n here allows the program to reach this line of code and 
cout << "test2\n"; //everything before it

Something strange is happening. Unless "\n" is included in the string nothing will print to standard out. For example. the cout << "test" & "test2\n" at the bottom enables the program to reach those lines of code and will cout everything up to that point, e.g. the "file opened" line because test2 has \n and file opened precedes it. If they are changed to just cout "test1" test2" the program will not output anything, including the "file opened". Additionally, if I change "file opened" to "file opened\n" then that will print, but if the test1 and test2 do not have a \n they will not print, since they are after the \n in "file opened."

melpomene
  • 84,125
  • 8
  • 85
  • 148

2 Answers2

1

Streams have buffering to avoid having to do large numbers of small I/O operations. By default, cout is line-buffered, so an end of line flushes the buffer. You can also explicitly flush the buffer and all buffers are flushed (that is, their contents are sent to their destinations) upon normal termination. If our program crashes or terminates abnormally, buffers will not be flushed.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

I suspect that your evidence that the program is stopping/freezing is limited to the fact that it doesn't produce the expected output. You could attack this problem with a source level debugger, to get a better sense of what the program is doing when it isn't printing anything.

Adding, "print statements" can also be a useful means of debugging, but you have to do it correctly (which usually requires that you include \n). Personally, I prefer to use std::cerr for debugging, one reason being that it automatically flushes each output regardless of whether or not you include the \n. Here's an example using cerr:

using std::cerr;
cerr<<"Unrecognized commands\n";

Fundamentally though, why would you want to cout these strings without a trailing \n? \n is the newline character. Without it, all of your outputs will be run together on the same line -- without even having intervening space characters:

file opened.testtest2

If you want to dive deeper, here's some related reading on buffering of stdout (specifically in 'C' though): Is stdout line buffered, unbuffered or indeterminate by default?

Community
  • 1
  • 1
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173