Object

Write a program that reads a string from a file and prints it on the screen.
(download example9.txt)

Algorithm

  1. Create an ifstream object inFile to handle input operations on a file.
  2. Declare a string variable line.
  3. Open the file named example9.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 getline() returns False
    • Write each line onto the screen.
    • [End of WHILE loop.]
  6. Close the file.
  7. Exit.

Flowchart

C++ Source Code

// program 112
#include<iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream inFile("example9.txt");
  if (!inFile.is_open())
  {
    cout << "Error: Unable to open the file" << endl;
    return 1;
  }

  string line;
  while (getline(inFile, line))
  {
    cout << line << endl;
  }
  inFile.close();
  
  return 0;
}

C Source Code

/*program 112*/
#include<stdio.h>
#include<stdlib.h>

int main()
{
  FILE *fptr;
  char string[800];

  if((fptr = fopen("example9.txt","r"))==NULL)
  {
     puts("Error: Unable to open the file");
     exit(1);
  }
  while(fgets(string, 799, fptr) != NULL)
     printf(string);
  fclose(fptr);
  
  return 0;
}

Output

What is stream in C++?
Stream refers to a stream of characters to be transferred between program thread and i/o.

Design a site like this with WordPress.com
Get started