Object

Write a program that writes one character at a time to a file until enter key is pressed.

Algorithm

  1. Create an ofstream object outFile to handle output operations on a file.
  2. Declare character variable ch.
  3. Open the file named example5.txt using outFile.open().
  4. IF the file fails to open,
    • Write “Error: Unable to open the file”.
    • Exit.
    • [End of IF structure.]
  5. WHILE ch ≠ New line (i.e., Enter key is pressed)
    • Reads each character using cin.get() and stores it in ch variable.
    • Write ch.
    • [End of WHILE loop.]
  6. Close the file.
  7. Exit.

Flowchart

C++ Source Code

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

int main()
{
  ofstream outFile; // File stream object
  char ch;

  outFile.open("example5.txt");	// Open the file for writing
  if (!outFile.is_open()) // Check if the file is open
  {
    cout << "Error: Unable to open the file" << endl;
    return 1;
  }

  cout << "Write text to file and press enter:\n\n";
  while (ch != '\n')
  {
    ch = cin.get();;
    outFile.put(ch);
  }
  outFile.close();

  return 0;
}

C Source Code

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

int main()
{
  FILE *fptr;
  char ch;
  fptr = fopen("example5.txt", "w");
  if(fptr==NULL)
     {
     printf("Error: Unable to open the file");
     exit(1);
     }
  printf("Write text to file and press enter:\n\n");
  while(ch != '\n')
     {
     ch=getchar();
     fputc(ch, fptr);
     }
  fclose(fptr);

  return 0;
}

Output

Write text to file and press enter:

Karachi is a beautiful city.

Design a site like this with WordPress.com
Get started