C++ – How to output variable’s declared as a double to a text file in C++

cfstreamiostream

I am very new to C++ and I am wondering how you output/write variables declared as double to a txt file. I know about how to output strings using fstream but I cant figure out how to send anything else. I am starting to think that you can't send anything but strings to a text file is that correct? If so then how would you convert the information stored in the variable to a string variable?

Here is my code that I'm trying to implement this concept into, Its fairly simple:

int main()
{

double invoiceAmt = 3800.00;
double apr = 18.5;            //percentage

//compute cash discount
double discountRate = 3.0;    //percentage
double discountAmt;

discountAmt = invoiceAmt * discountRate/100;

//compute amount due in 10 days
double amtDueIn10;

amtDueIn10 = invoiceAmt - discountAmt;

//Compute Interest on the loan of amount (with discount)for 20 days
double LoanInt;

LoanInt = amtDueIn10 * (apr /360/100) * 20;

//Compute amount due in 20 days at 18.5%.
double amtDueIn20;

amtDueIn20 = invoiceAmt * (1 + (apr /360/100) * 20);
return 0;
}

So what I'm trying to do is use those variables and output them to the text file. Also please inform me on the includes that I need to use for this source code. Feel free to give suggestions on how to improve my code in other ways as well please.

Thanks in advance.

Best Answer

As your tagging suggests, you use file streams:

std::ofstream ofs("/path/to/file.txt");
ofs << amtDueIn20;

Depending on what you need the file for, you'll probably have to write more stuff (like whitespaces etc.) in order to get decent formatting.

Edit due to rmagoteaux22's ongoing problems:

This code

#include <iostream>
#include <fstream>

const double d = 3.1415926;

int main(){
    std::ofstream ofs("test.txt");
    if( !ofs.good() ) {
        std::cerr << "Couldn't open text file!\n";
        return 1;
    }
    ofs << d << '\n';
    return 0;
}

compiles for me (VC9) and writes this to test.txt:

3.14159

Can you try this?