Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file setprecision c++ code

Tags:

c++

file

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;
}
like image 789
user3214262 Avatar asked Jan 20 '14 08:01

user3214262


People also ask

What is Setprecision in C?

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.

What is the header file for Setprecision?

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>.

What is the library of Setprecision in C++?

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.


1 Answers

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

like image 55
Mats Petersson Avatar answered Oct 05 '22 14:10

Mats Petersson