Search code examples
c++iostreamfstream

Program will not print line before exit() function?


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);
    }

Solution

  • 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;