I had this code in C++ that is working just fine, first it ask the user for a file name, and then saves some number in that file.
But what I am trying to do is to save numbers with two decimal places, e.g the
user types 2
and I want to save the number 2
, but with two decimal places
2.00
.
Any ideas of how to do that?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
double num;
double data;
string fileName = " ";
cout << "File name: " << endl;
getline(cin, fileName);
cout << "How many numbers do you want to insert? ";
cin >> num;
for (int i = 1; i <= num; i++) {
ofstream myfile;
myfile.open(fileName.c_str(), ios::app);
cout << "Num " << i << ": ";
cin >> data;
myfile << data << setprecision(3) << endl;
myfile.close();
}
return 0;
}
The C++ setprecision function is used to format floating-point values. This is an inbuilt function and can be used by importing the iomanip library in a program.
C++ manipulator setprecision function is used to control the number of digits of an output stream display of a floating- point value. This manipulator is declared in header file <iomanip>.
The setprecision() method of iomanip library in C++ is used to set the ios library floating point precision based on the precision specified as the parameter to this method. Parameters: This method accepts n as a parameter which is the integer argument corresponding to which the floating-point precision is to be set.
Ok, you need to use setprecision
before the data is written.
I would also move the open and close of the file out of the loop (and the declaration of myfile
, of course, as it's generally a fairly "heavy" operation to open and close a file inside a loop like this.
Here's a little demo that works:
#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ofstream f("a.txt", std::ios::app);
double d = 3.1415926;
f << "Test 1 " << std::setprecision(5) << d << std::endl;
f << "Test 2 " << d << std::endl;
f << std::setprecision(7);
f << "Test 3 " << d << std::endl;
f.precision(3);
f << "Test 3 " << d << std::endl;
f.close();
}
Note however that if your number is for example 3.0, then you also need std::fixed
. E.g. if we do this:
f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;
it will show 3.00000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With