Object

Write a program that reads formatted data from a file.
(download example6.txt)

Algorithm

  1. Create an ifstream object inFile to handle input operations on a file.
  2. Declare a string variable str.
  3. Open the file named example6.txt using inFile.open().
  4. IF the file fails to open,
    • Write “Error: Unable to open the file”.
    • Exit.
    • [End of IF structure.]
  5. WHILE inFile ≠ End of file
    • Write each line onto the screen.
    • [End of WHILE loop.]
  6. Close the file.
  7. 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 
Design a site like this with WordPress.com
Get started