Writing to Sequential Access File with Fixed Point Notation

I was wondering how to write a sequential access text file using fixed point notation to 2 decimal places. What I tried in my code did not work, when I inputted 20 it appeared as 20 in the text file, when it should be 20.00.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* Arooj Mohammed	C++ Ch13Ex16

*/

//Ch13Ex16.cpp – saves the prices of inventory items 
//in a sequential access file

#include <iostream>
#include <iomanip>
#include <fstream>

using std::cout;
using std::cin;
using std::endl;
using std::setprecision;
using std::setiosflags;
using std::ofstream;
using std::ios;

int main()
{	
	//declare variable
	double price = 0.0;

	//create file object and open the file
	ofstream outFile;
	outFile.open("prices.txt", ios::app);
	//determine whether the file was opened
	if (outFile.is_open())
	{

		//write output in fixed-point notation
		//with two decimal places
		

		//get the prices and
		//write each to the file
		cout << "Enter item price (-1 to stop): ";
		cin >> setiosflags(ios::fixed) >> setprecision(2) >> price;
		while (price != -1)
		{
			cin.ignore();
			outFile << price << endl;
			cout << "Enter item price (-1 to stop): ";
			cin >> setiosflags(ios::fixed) >> setprecision(2) >> price;

		} //end while

		//close the file
		outFile.close();

} //end if
	
	else
		cout << "File could not be opened." << endl;

    return 0;
}   //end of main function 


text file

10.5
15.99
20
76.54
17.34
One option would be to detect the number of digits in the decimal part of the number, then setw(digits + 3). To get the number of digits, you can truncate the price to an int (add something like 1e-10 first to avoid rounding errors), put it in a stringstream, and check the length of the string.
Try using fprintf (f1, ".........");
f1 being the file stream
so..

fprintf (outFile, "%5.2f", itemPrice);

the % marks where to replace, in order, the variables listed after the string, the 5 is how many characters to set the column width to hold and the 2 is the precision.
the outFile in fprintf (outFile, "%5.2f", itemPrice); experiences an error stating no suitable conversion from ofstream to FILE exists.
Is there any way I can use std:setiosflags and std:setprecision to write it to the file fixed and with two decimal places, so its like 10.50 instead of my entering of 10.5?
Topic archived. No new replies allowed.