0

I am trying to save some double variables to a file, but I would like for them to save with only 2 decimal places. If I were going to print them to terminal I would do this:

printf ("var1: %.2f var2: %.2f\n", var1, var2);

I would like to know if there is an equivalent but to use while writing to a file with fstream.

I know in Java you can use PrintWriter, for something like that, but is there a C++ equivalent?

Also I know I am double dipping here, but if I could also get a Java FileWriter equivalent for C++ that would be great, because my program overwrites my file content, it doesn't append to it.

lokilindo
  • 682
  • 5
  • 17
  • 4
    What is `fprint`? The C standard library provides `fprintf` which is available in C++ too. And if you know how to use `std::cout`, you can do just the same thing with an `std::ofstream` to write to a file. – 5gon12eder Feb 14 '16 at 03:12
  • 2
    open the file with `fopen` and use `fprintf` instead of `printf` – M.M Feb 14 '16 at 03:14
  • 1
    in c++, you will want to use std::ofstream and formatted insert operators and io manipulators. see and – 2785528 Feb 14 '16 at 03:22
  • I am just beginning to use c++ and I don't know the syntax all that well, some sample code would be appreciated. – lokilindo Feb 14 '16 at 03:26
  • @5gon12eder I know I can use `ofstream`, but I don't just want to write to the file, I would like to string format as well. – lokilindo Feb 14 '16 at 03:28
  • For string formatting, you could use a `std::ostringstream` or `std::snprintf`. But please be specific and limit yourself to one question at a time. Your original question was asking about file output. – 5gon12eder Feb 14 '16 at 04:31
  • Have a look at the answers http://stackoverflow.com/questions/15106102/how-to-use-c-stdostream-with-printf-like-formatting and http://stackoverflow.com/questions/18263461/c-regarding-fprintf-and-ofstream Also there is some info http://horstmann.com/cpp/iostreams.html and http://www.flipcode.com/archives/ostream_printf.shtml and http://www.boost.org/doc/libs/1_58_0/libs/format/doc/format.html – Jerry Jeremiah Feb 16 '16 at 23:40

2 Answers2

3

If you write your file in C style (using FILE*), you can use fprintf().

For C++-style ostream output, such formatting is done with stream manipulators:

out << "var1: " << std::fixed << std::setprecision(2) << var1 << " var2: " << var2;

Sometimes this is inconvenient (such as when the format is language-dependent, and you need to retrieve it from the translation file).

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
2

You can use snprintf to format the string in memory, then write it to the ofstream via <<.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62