Object
Write a program that writes formatted data into a file.
(download example6.txt)
Algorithm
- Create an ofstream object outFile to handle output operations on a file.
- Declare a character variable flag and string, name up to 30 characters.
- Declare integer variable quantity and float variable cost.
- Open the file named example6.txt using outFile.open().
- IF the file fails to open,
- Write “Error: Unable to open the file”.
- Exit.
- [End of IF structure.]
- Set flag = ‘y’.
- WHILE flag ≠ ‘n’
- Read name, cost and quantity.
- Write name, cost and quantity.
- Read flag.
- [End of WHILE loop.]
- Close the file.
- Exit.
Flowchart

C++ Source Code
// program 113
#include<iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile("example6.txt");
char flag, name[30];
int quantity;
float cost;
if (!outFile.is_open())
{
cout << "Error: Unable to open the file" << endl;
return 1;
}
flag = 'y';
while (flag != 'n')
{
cout << "Please enter the item name: ";
cin.getline(name, 30);
cout << "Please enter the cost: ";
cin >> cost;
cout << "Please enter the quantity: ";
cin >> quantity;
outFile << left << setw(30) << name << fixed << setprecision(2) << setw(10) << cost << setw(10) << quantity << endl;
cout << "\nDo you have another item name? (y/n): ";
cin >> flag;
cin.ignore(); // Ignore the newline character in the input buffer
}
outFile.close();
return 0;
}
C Source Code
/*program 113*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char flag, name[30];
int quantity;
float cost;
if((fptr = fopen("example6.txt","w"))==NULL)
{
puts("Error: Unable to open the file");
exit(1);
}
flag = 'y';
while(flag != 'n')
{
printf("Please enter the item name: ");
gets(name);
printf("Please enter the cost: ");
scanf("%f", &cost);
printf("Please enter the quantity: ");
scanf("%d", &quantity);
fprintf(fptr, "%s\t %.2f\t %d\n", name, cost, quantity);
printf("\nDo you have another item name: (y/n) ");
scanf(" %c", &flag);
while (getchar() != '\n'); // Clear input buffer
printf("\n");
}
fclose(fptr);
}
Output
Input given
Please enter the item name: Hard disk
Please enter the cost: 25.5
Please enter the quantity: 100
Do you have another item name? (y/n): y
Please enter the item name: Network cable
Please enter the cost: 75.0
Please enter the quantity: 15
Do you have another item name? (y/n): y
Please enter the item name: Printer toner
Please enter the cost: 85.25
Please enter the quantity: 3
Do you have another item name? (y/n): n
Output
Hard disk 25.50 100 Network cable 75.00 15 Printer toner 85.25 3
