1

I have a little project for school I am writing in C++, and we have to account for some error and just exit the program in the event that it happens. Basically, in the else statement when the expression is evaluated as false, it's like it won't write to the file the error. If I output it to the console (via cout) instead of writing it to the file it works just fine, but when I try to write it to the output file, it does not work. Basically, that is my question. My professor is requiring that all output is to the file, that's why I can't use cout. So why will it output it to the console, and not to the file?

P.S. I am outputting other stuff to the file and it's working fine, so for the record I think it is narrowed down to the little block of code in the else statement.

if(tempUnit == 'C' || tempUnit == 'F')
    {
      if(tempUnit == 'F')
      {
        temp = convertTemp(temp, tempUnit);
      }

      temps[a] = temp;

      printTemp(outputFile, tempUnit, temp);
      printTimestamp(outputFile, humanDate);

      outputFile << endl;

    }
    else{
      // this is where it doesnt work
      outputFile << "Error. Incorrect temperature unit, must be " << 
      "either a capital C or a capital F. Program ended.";
      exit(0);
    }
Eric Diviney
  • 327
  • 2
  • 5
  • 16

2 Answers2

5

You need to flush the buffer before exiting the program.

outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::flush;

or

outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::endl;
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • Worked perfect. I'll accept the answer as soon as it let's me. Just curious, where did you learn this? I'd like to read about some of the odd things like this that a c++ developer would need to know. Just so I don't have to ask a stack overflow question everytime I run into a small thing like this. – Eric Diviney Jan 27 '14 at 19:31
  • @EricDiviney This is something a C++ primer should cover when it talks about output streams. `std::cout` and `std::ofstream` (and others) are buffered. If you exit the program too quickly, the data in their buffers will not be pushed to the output - so you must force it to prior to closing the program. – Zac Howland Jan 27 '14 at 19:32
  • Thanks very much for the quick and precise answer. Definitely appreciate your help today! – Eric Diviney Jan 27 '14 at 19:34
1

Both stdout and stderr are buffered. You need to tell your program to flush your output file.

If you were doing C, you would,

fflush(stdout);
//or
fflush(stderr);

Since you are doing C++, you spell fflush, endl,

cout << std::endl; // endl does the flushing

see this stackoverflow: endl

Community
  • 1
  • 1
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42