views:

343

answers:

7

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.

+5  A: 

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?

sbi
I have done lots of research and learned about this source code to do so but I could only seem to get it to work if it was written with a string rather than a variable. Any suggestions as to why?
MSalters
It still didn't work... This is the code that I tried: ofstream outFile("Program1.txt"); outFile << "Discount Amount: \n"; outFile << amtDueIn10; outFile << "Amount Due in 20 Days: \n"; outFile << amtDueIn20;
oh and I have outFile.close(); at the end so its not that
@rmagoteaux22 sbi's code should work, if it still doesn't it's probably due to wrong includes. It's rather hard to know what you missed, please post the error message from your compiler.
Pieter
Thats the thing though my compiler is not displaying any errors, I've been at this for many hours and I cant seem to find the problem.
Ok I tried that and it compiled fine and had no errors, but nothing was in the text file... :/
What compiler are you using? Are you compiling with all warnings turned on?
Kristo
yes, Im starting to think its my IDE, I am using Xcode on my macbook Pro
Delete the output file. Run the program. Is the file created again?
sbi
I found out what the problem was haha such a simple thing set me back hours and hours lol Being new to Xcode and all I was compiling and running in debug mode and didnt realize it, as soon as i change it to release mode it worked.
No, this wasn't your problem. (It should work in Debug mode just as well.) You just hid the problem, but it's still lurking somewhere, waiting to jump at you when you least expect it.
sbi
+1  A: 

Look at this question

Traveling Tech Guy
I have already seen that question actually haha I have tried both ways listed there in green. I even tried the boost was after installing the header files and using Lixical_cast. I was unable to get that to work as well.
A: 

To answer your first question, in C you use printf (and for file output fprintf). IIRC, cout has a large number of modifiers also, but I won't mention them as you originally mentioned fstream (more 'C' centric than C++) --


oops, missed the ofstream indicator, ignore my 'C' comments and use C++


to improve your program, be sure to use parentheses a lot when doing computations as above to be 100% sure things are evaluated the way you want them to be (do not rely on order of precedence)

KevinDTimm
fstream "more 'C' centric"? It's a stream class, with the << operator and everything. Same interface as cout.
Sam Stokes
Thank you for the tips, much appreciated
Sam, your comment and my edit must have crossed in the mail :)
KevinDTimm
A: 

Generally speaking methods to write to a output are printf, wprintf etc.

In case of files, these methods are named as fprintf_s, fsprintf_s etc.

Note that the '_s' methods are the new secure variations of previous formatting methods. You should always use these new secure versions.

For examples refer to: http://msdn.microsoft.com/en-us/library/ksf1fzyy%28VS.80%29.aspx

Note these methods use a format specifier to convert a given type to text. For example %d acts as a place holder for integer. Similarly %f for double.

Sesh
+1  A: 

Simply use the stream write operator operator<< which has an overloaded definition for double (defined in basic_ostream)

#include <fstream>

...


    std::fstream stmMyStream( "c:\\tmp\\teststm.txt", std::ios::in | std::ios::out | std::ios::trunc );

    double dbMyDouble = 23.456;
    stmMyStream << "The value is: " << dbMyDouble;
snowdude
I used the code you provided and tested it out and All that was written to my text file was "The value is: ". The variable did not display at all. Please Help
A: 

Just use the << operator on an output stream:

#include <fstream>

int main() {
  double myNumber = 42.5;
  std::fstream outfile("test.txt", std::fstream::out);
  outfile << "The answer is almost " << myNumber << std::endl;
  outfile.close();
}
Sam Stokes
A: 

I was having the exact same problem, where ofstream was outputting strings, but stopped as soon as it reached a variable. With a bit more Googling I found this solution in a forum post:

Under Xcode 3.2 when creating a new project based on stdc++ project template the target build settings for Debug configuration adds preprocessor macros which are incompatible with gcc-4.2: _GLIBCXX_DEBUG=1 _GLIBXX_DEBUG_PEDANTIC=1

Destroy them if you want Debug/gcc-4.2 to execute correctly.

http://forums.macrumors.com/showpost.php?p=8590820&amp;postcount=8