2

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.

sbi
  • 219,715
  • 46
  • 258
  • 445
user168427
  • 25
  • 1
  • 7
  • 2
    As a general note, since you might be new to programming (and not only C++); it's generally not a good idea to use floating-point for money computations. You want your money handled as exactly as possible, and floating-point computations just aren't up to the task. – unwind Sep 04 '09 at 10:22
  • Well I'm actually not new to programming, I have learned Java and vb but that was 2 years ago now so its been a while. And the reason for the doubles is this was a class assignment and my professor for some reason wanted them declared that way. – user168427 Sep 04 '09 at 10:47

6 Answers6

6

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
  • 219,715
  • 46
  • 258
  • 445
  • 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? – user168427 Sep 04 '09 at 10:41
  • You're likely forgetting to `#include ` (header with functions for output streams). You probably got `std::ofstream` through `fstream` and `operator<<(std::ostream&, std::string)` through `` – MSalters Sep 04 '09 at 10:46
  • 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; – user168427 Sep 04 '09 at 11:00
  • oh and I have outFile.close(); at the end so its not that – user168427 Sep 04 '09 at 11:08
  • @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 Sep 04 '09 at 11:18
  • 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. – user168427 Sep 04 '09 at 11:20
  • Ok I tried that and it compiled fine and had no errors, but nothing was in the text file... :/ – user168427 Sep 04 '09 at 11:45
  • What compiler are you using? Are you compiling with all warnings turned on? – Michael Kristofik Sep 04 '09 at 11:46
  • yes, Im starting to think its my IDE, I am using Xcode on my macbook Pro – user168427 Sep 04 '09 at 11:49
  • Delete the output file. Run the program. Is the file created again? – sbi Sep 04 '09 at 12:06
  • 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. – user168427 Sep 04 '09 at 12:10
  • 3
    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 Sep 04 '09 at 12:19
1

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
  • 3,854
  • 1
  • 18
  • 27
  • 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 – user168427 Sep 04 '09 at 11:18
0

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
  • 14,226
  • 3
  • 42
  • 60
0

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
  • 5,993
  • 4
  • 30
  • 39
0

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
  • 14,617
  • 7
  • 36
  • 33
0

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&postcount=8