How to Use a Temporary Buffer in C++

C++ is an object-oriented, systems programming language designed to allow programmers to develop applications and utilities for desktop operating systems. C++ programs often deal with raw data, such as textual input, in large quantities. In cases such as this, it would not be feasible to bring an entire set of data into the program. Rather, you set up a temporary buffer to hold intermediate results while they are processed.

Things You'll Need

  • C++ compiler
  • Text editor
Show More

Instructions

    • 1

      Create the buffer. For example, you know your program will receive a large number of integers in an unknown sequence from a file. You decide to create a buffer of 100 integers that will hold input until they are processed. This is accomplished through the "new" keyword and a pointer.

      #include <fstream>
      #include <iostream>
      using namespace std;

      int main(){

      int buffer_size = 1024; //buffer is 1024 in size
      int * buff;

      buff = new int [buffer_size];
      return 0;
      }

    • 2

      Import a file consisting of integers and named, for example, "ints.txt" into the program. The goal of this script will be to read from this file, filling the buffer, processing the data from the buffer, and emptying it again:

      ifstream in;
      in.open("ints.txt");

    • 3

      Read data into the buffer. Using the "read" function, read 1024 integers from the file, fill the buffer, and print the integers to the screen. The read function can be used again to get the next set of integers from the file.

      in.read(buff, buffer_size);
      for (int i = 0; i < buffer_size; i++){
      cout << buff[i];
      }

Related Searches:

References

Comments

Related Ads

Featured