Object
Write a program that reads formatted data from a file.
(download example6.txt)
Algorithm
- Create an ifstream object inFile to handle input operations on a file.
- Declare a string variable str.
- Open the file named example6.txt using inFile.open().
- IF the file fails to open,
- Write “Error: Unable to open the file”.
- Exit.
- [End of IF structure.]
- WHILE inFile ≠ End of file
- Write each line onto the screen.
- [End of WHILE loop.]
- Close the file.
- Exit.
Flowchart

C++ Source Code
// program 114
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile("example6.txt");
if (!inFile.is_open())
{
cout << "Error: Unable to open the file" << endl;
return 1;
}
else
{
string str;
while (!inFile.eof())
{
getline(inFile, str);
cout << str << endl;
}
}
inFile.close();
return 0;
}
C Source Code
/*program 114*/
#include <stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char str[100];
if((fptr = fopen("example6.txt","r"))==NULL)
{
puts("Error: Unable to open the file");
exit(1);
}
else
{
while (fgets(str, sizeof(str), fptr) != NULL)
{
printf("%s", str);
}
}
fclose(fptr);
return 0;
}
Output
Hard disk 25.50 100 Network Cable 75.00 15 Printer toner 85.25 3
