Write up on Tech Geek HISTORY: C++ Programming LANGUAGE (rEVISION 3)

Literature Review

As a Bell Labs employee, Bjarne Stroustrup was exposed to and appreciated the strengths of C, but also appreciated the power and convenience of higher-level languages like Simula, which had language support for object-oriented programming (OOP). Stroustrup realized that there was nothing in the nature of C that prevented it from directly supporting higher-level abstractions such as OOP or type programming. He wanted a language that provided programmers with both elegance when expressing high-level ideas and efficiency of execution size and speed. He worked on developing his own language, originally called C With Classes, which, as a superset of C, would have the control and power of portable assembler, but which also had extensions that supported the higher-level abstractions that he wanted from Simula

The extensions that he created for what would ultimately become known as C++ allowed users to define their own types. These types could behave (almost) like the built-in types provided by the language, but could also have the inheritance relationships that supported OOP

Alex Stepanov was using C++ templates to create what would even tually become known as the Standard Template Library (STL). Ste panov was exploring a paradigm he called generic programming. Generic programming is “an approach to programming that focuses on designing algorithms and data structures so that they work in the most general setting without loss of efficiency.” [FM2G] Although the STL was a departure from every other library at the time, Andrew Koenig, then the chair of the Library Working Group for the ISO C++ Standards Committee, saw the value in it and invi ted Stepanov to make a submission to the committee. Stepanov was skeptical that the committee would accept such a large proposal when it was so close to releasing the first version of the standard. Koenig asserted that Stepanov was correct. The committee would not accept it…if Stepanov didn’t submit it. Stepanov and his team created a formal specification for his library and submitted it to the committee. As expected, the committee felt that it was an overwhelming submission that came too late to be accepted

In 1998, the committee released the first ISO standard for C++. It standardized “classic” C++ with a number of nice improvements and included the STL, a library and programming paradigm clearly ahead of its time. One challenge that the Library Working Group faced was that it was tasked not to create libraries, but to standardize common usage. The problem it faced was that most libraries were either like the STL (not in common use) or they were proprietary (and therefore not good candidates for standardization).

Also in 1998, Beman Dawes, who succeeded Koenig as Library Working Group chair, worked with Dave Abrahams and a few other members of the Library Working Group to set up the Boost Libra ries.4 Boost is an open source, peer-reviewed collection of C++ libra ries,5 which may or may not be candidates for inclusion in the standard. Boost was created so that libraries that might be candidates for standardization would be vetted (hence the peer reviews) and popu larized (hence the open source). Although it was set up by members of the Standards Committee with the express purpose of developing candidates for standardiza tion, Boost is an independent project of the nonprofit Software Freedom Conservancy.6 With the release of the standard and the creation of Boost.org, it seemed that C++ was ready to take off at the end of the ʽ90s. But it didn’t work out that way

In 2011, the first major revision to Standard C++ was released, and it was very clear that the ISO Committee had not been sitting on its hands for the previous 13 years. The new standard was a major update to both the core language and the standard library.4 The update, which Bjarne Stroustrup, the creator of C++, reported “feels like a new language,”5 seemed to offer something for everyone. It had dozens of changes, some small and some fundamental, but the most important achievement was that C++ now had the features programmers expected of a modern language

After the standard was completed in 1997, several formal motions by different countries made it an international ISO and ANSI standard in 1998. The standardization process included the development of a C++ standard library. The library extends the core language to provide some general components. By using C++’s ability to program new abstract and generic types, the library provides a set of common classes and interfaces. This gives programmers a higher level of abstraction. The library provides the ability to use

• String types

 • Different data structures (such as dynamic arrays, linked lists, and binary trees)

 • Different algorithms (such as different sorting algorithms)

• Numeric classes

 • Input/output (I/O) classes

• Classes for internationalization support All of these are supported by a fairly simple programming interface. These components are very important for many programs. These days, data processing often means inputting, computing, processing, and outputting large amounts of data, which are often strings.

The core language and the library of C++ were standardized in parallel. In this way, the library could benefit from improvements in the language and the language could benefit from experiences of library implementation. In fact, during the standardization process the library often used special language features that were not yet available. C++ is not the same language it was five years ago. If you didn’t follow its evolution, you may be surprised with the new language features used by the library. This section gives you a brief overview of those new features. For details, refer to books on the language in question. While I was writing this book (in 1998), not all compilers were able to provide all of the new language features. I hope (and expect) that this will change very soon (most compiler vendors were part of the standardization process). Thus, you may be restricted in your use of the library. Portable implementations of the library typically consider whether features are present in the environment they use (they usually have some test programs to check which language features are present, and then set preprocessor directives according to the result of the check). I’ll mention any restrictions that are typical and important throughout the book by using footnotes. The following subsections describe the most important new language features that are relevant for the C++ standard library.

Almost all parts of the library are written as templates. Without template support, you can’t use the standard library. Moreover, the library needed new special template features, which I introduce after a short overview of templates. 14 dyne-book The C++ Standard Library Templates are functions or classes that are written for one or more types not yet specified. When you use a template, you pass the types as arguments, explicitly or implicitly. The following is a typical example — a function that returns the maximum of two values:

Template<Class t>

inline const T& max (const T& a, const T& b)

{

// if a<b  then use b else use a

return a < b ? b : a;

}

https://resources.jetbrains.com/storage/products/cpp/books/Cplusplus_Today.pdf

Here, the first line defines T as an arbitrary data type that is specified by the caller when the caller calls the function. You can use any identifier as a parameter name, but using T is very common, if not a de facto convention. The type is classified by class, although it does not have to be a class. You can use any data type as long as it provides the operations that the template uses.[3]

https://www.cesarkallas.net/arquivos/livros/informatica/cpp/The%20C%2B%2B%20Standard%20Library.pdf

Standard Library Algorithms What is an algorithm? A general definition of an algorithm is ‘‘a finite set of rules which gives a sequence of operations for solving a specific set of problems [and] has five important features: Finiteness … Definiteness … Input … Output … Effectiveness’’ [Knuth,1968,§1.1]. In the context of the C++standard library, an algorithm is a set of templates operating on sequences of elements. The standard library provides dozens of algorithms.

https://www.stroustrup.com/3rd_tour2.pdf

The algorithm library in the C++ Standard Library is a cornerstone for writing efficient and readable code. Algorithms are pre-defined methods that perform computations on ranges of data, which are typically specified by iterators. This aspect of the library is pivotal as it provides a standardized set of tools for operations like searching, sorting, and modifying data elements, thereby ensuring consistency and efficiency across C++ programs. One of the key advantages of using the algorithm library is its ability to abstract complex operations into simple function calls. This not only enhances code readability but also leverages highly optimized implementations that are often better than custom-built solutions. The algorithms encompass a wide range of functionalities, but some of the most commonly used categories include searching, sorting, and manipulating collections of data. Searching algorithms are fundamental for locating specific elements within a collection.

Understanding the role of iterators in the C++ Standard Library is crucial for efficiently bridging the world of algorithms and containers. Iterators are a generalized way to access elements stored in various container types, enabling a uniform approach to traverse and manipulate these elements. By understanding different types of iterators and their functionalities, developers can leverage the full power of the C++ algorithms and container classes. At its core, an iterator is an object that points to an element within a container and allows the traversal of elements without exposing the underlying structure of the container. Iterators provide an abstraction by defining how elements are accessed sequentially; they can be thought of as a generalized pointer. The five primary categories of iterators are:

**Input Iterators**: Designed for reading data from the container sequentially

2. **Output Iterators**: Serve the purpose of writing data to the container sequentially

3. **Forward Iterators**: Combine the capabilities of input and output iterators, allowing read/write operations and traversal in a single direction.

 4. **Bidirectional Iterators**: Extend forward iterators to support traversal in both directions (forward and backward).

5. **Random Access Iterators**: Provide all functionalities of bidirectional iterators with additional capabilities to jump directly to any element within the container in constant time (similar to pointer arithmetic)

The C++ Standard Library offers robust support for strings, streams, and input/output (IO) operations, which are critical aspects of many applications.

The Standard Library provides several stream classes, including `std::cin`, `std::cout`, and `std::cerr`, among others.

 **Basic IO Operations:**- Input: `std::cin` is commonly used to read data from standard input, typically via the extraction operator (`>>`).

 – Output: `std::cout` outputs data to the standard output, using the insertion operator (`<

**File Streams:** The library includes `std::ifstream` and `std::ofstream` for reading from and writing to files, respectively. `std::fstream` supports both input and output operations. **File Operations:

**- Opening and Closing Files: The `open()` method accepts a filename and an optional mode (e.g., input, output, append), and the `close()` method terminates the connection with th

file.- Reading and Writing: Utilize the same operators and methods as standard IO streams (`>>` (`>>` for reading and `<  <writing )

https://cdn.bookey.app/files/pdf/book/en/the-c—standard-library.pdf

Chapter 1:

Reading and writing are fundamental to file processing; they are the actions that make file processing an input/output (I/O) operation. The form of the read and write statements used in different languages varies. Some languages provide very high-level access to reading and writing and automatically take care of details for the programmer. Other languages provide access at a much lower level. Our use of C and C++ allows us to explore some of these differences.

We begin with reading and writing at a relatively low level. It is useful to have a kind of systems-level understanding of what happens when we send and receive information to and from a file. A low-level read call requires three pieces of information, expressed here as arguments to a generic Read function: Read (Source_file, Destination_addr, Size)

Source_file The Read call must know where it is to read from. We specify the source by logical file name (phone line) through which data is received. (Remember, before we do any reading, we must have already opened the file so the connection between a logical file and a specific physical file or device exists.)

Destination_addr Read must know where to place the information it reads from the input file. In this generic function we specify the destination by giving the first address of the memory block where we want to store the data. Size Finally, Read must know how much information to bring in from the file. Here the argument is supplied as a byte count.

Write statement is similar; the only difference is that the data moves in the other direction: Write (Destination_file, Source_addr, Size) Destination_file The logical file name that is used for sending the data.

 Source_addr

Size Writemust know where to find the information it will send. We provide this specification as the first address of the memory block where the data is stored. The number of bytes to be written must be supplied.

Files with C Streams and C++ Stream Classes I/O operations in C and C++ are based on the concept of a stream, which can be a file or some other source or consumer of data. There are two different styles for manipulating files in C++. The first uses the standard C functions defined in header file stdio.h.

This is often referred to as C streams or C input/output. The second uses the stream classes of header files iostream.hand fstream. h. We refer to this style as C++ stream classes. The header file stdio.h contains definitions of the types and the operations defined on C streams. The standard input and output of a C program are streams called stdin and stdout, respectively.

 Other files can be associated with streams through the use of the fopen function: file = fopen (filename, type); The return value file and the arguments filename and type have the following meanings: Argument Type Explanation file FILE * filename char * type char * A pointer to the file descriptor.

 Type FILE is another name for struct iobuf. If there is an error in the attempt to open the file, this value is null, and the variable errno is set with the error number. The file name, just as in the Unix open function. The type argument controls the operation of the open function, much like the flags argument to open. The following values are supported: “r” Open an existing file for input. “W” Create a new file, or truncate an existing one, for output.

https://sunilwanjarisvpcet.wordpress.com/wp-content/uploads/2020/03/file_structures_an_object-oriented_approch.pdf

1.0 Standard I/O and file streams The most commonly used library is the I/O stream library.

Every program in the text includes iostream, in order to display output using the cout stream. The iostream interface is extended in the fstream interface with additional features that make it possible to read and write files, which in turn enable you to store data values that persist even after your program completes its operation. Data files Whenever you want to store information on the computer for longer than the running time of a program, the usual approach is to collect the data into a logically cohesive whole and store it on a permanent storage medium as a file. Ordinarily, a file is stored using magnetic or optical media, such as on a removable floppy disk, a compact disc, or a hard disk. The important point is that the permanent data objects you store on the computer—documents, games, executable programs, source code, and the like—are all stored in the form of files. On most systems, files come in a variety of types. For example, in the programming domain, you work with source files, object files, and executable files, each of which has a distinct representation. When you use a file to store data for use by a program, that file usually consists of text and is therefore called a text file. You can think of a text file as a sequence of characters stored in a permanent medium and identified by a file name. The name of the file and the characters it contains have the same relationship as the name of a variable and its contents.

When you look at a file, it is often convenient to regard it as a two-dimensional structure—a sequence of lines composed of individual characters. Internally, however, text files are represented as a one-dimensional sequence of characters. In addition to the printing characters you can see, files also contain the newline character ‘\n’, which marks the end of each line. The file system also keeps track of the length of the file so programs that read files can recognize where the file ends. In many respects, text files are similar to strings. Each consists of an ordered collection of characters with a specified endpoint. On the other hand, strings and files differ in several important respects. The most important difference is the permanence of Libraries and Interfaces – 106 – the data. A string is stored temporarily in the computer’s memory during the time that a program runs; a file is stored permanently on a long-term storage device until it is explicitly deleted. There is also a difference in the way you use data in strings and files. The individual characters in a string may be accessed in any order by specifying the appropriate index. The characters in a text file are usually accessed in a sequential fashion, with a program starting at the beginning of the file and either reading or writing characters from the start to the end in order. Using file streams in C++ To read or write a file as part of a C++ program, you must use the following steps:

Declare a stream variable. The fstream interface exports two types, ifstream, for files being read from, and ofstream, for files being written to. Each type keeps track of the information the system needs to manage file processing activity. Thus, if you are writing a program that reads an input file and creates a second file for output, you need to declare two variables, as follows: ifstream infile; ofstream outfile;

2.  Open the file. Before you can use a stream variable, you need to establish an association between that variable and an actual file. This operation is called opening the file and is performed by calling the stream method open. Like the methods seen previously on string, you invoke it using dot notation on the stream. For example, if you wanted to read the text of the jabberwocky.txt file, you would execute the statement infile.open(“jabberwocky.txt”); One minor glitch to note is that the open method expects a C-style string as the argument. A string literal is acceptable as is, but if you have the filename in a C++ string variable, you will need to pass its C-style equivalent as shown: string str = … infile.open(str.c_str()); If a requested input file is missing, the open operation will fail. You can test the current state of a stream by using the fail method. As a programmer, you have a responsibility to check for this error and report it to the user. if (infile.fail()) Error(“Could not open file.”); In some cases, you may want to recover from such an input file failure (for example, if the user accidentally typed a non-existent filename), and try to open the input stream once again. In such cases, you must first clear the “fail state” that the input stream variable will be in after such a failure. You can do this by calling the clear method on the stream, as exemplified below

          infile.clear();

 3. Transfer the data. Once you have opened the data files, you then use the appropriate stream operations to perform the actual I/O operations. For an input file, these operations read data from the file into your program; for an output file, the operations transfer data from the program to the file. To perform the actual transfers, you can choose any of several strategies, depending on the application. At the simplest level, you can read or write files character by character. In some cases, however, it is more convenient to process files line by line. At a still higher level, you can choose to read

and write formatted data. Doing so allows you to intermix numeric data with strings and other data types.

4. Close the file. When you have finished all data transfers, you need to indicate that fact to the file system by calling the stream method close. This operation, called closing the file, breaks the association between a stream variable and the actual file. infile.close(); Standard streams The standard I/O library defines three special identifiers—cin, cout, and cerr—that act as stream variables and are available to all programs. These variables are referred to as standard streams. The constant cin designates the standard input stream, which is the source for user input. The constant cout indicates the standard output stream and represents the device on which output data is written to the user. The constant cerr represents the standard error stream and is used to report any error messages the user should see. Typically, the standard streams all refer to the computer console. When you read data from cin, the input comes from the keyboard; when you write data to cout or cerr, the output appears on the screen. You do not open or close these streams; they are handled automatically. Formatted stream outpu

Standard streams The standard I/O library defines three special identifiers—cin, cout, and cerr—that act as stream variables and are available to all programs. These variables are referred to as standard streams. The constant cin designates the standard input stream, which is the source for user input. The constant cout indicates the standard output stream and represents the device on which output data is written to the user. The constant cerr represents the standard error stream and is used to report any error messages the user should see. Typically, the standard streams all refer to the computer console. When you read data from cin, the input comes from the keyboard; when you write data to cout or cerr, the output appears on the screen. You do not open or close these streams; they are handled automatically. Formatted stream output Stream output is usually accomplished by using the insertion operator <<< “some text ” << num << endl;

The insertion operator will accept any primitive data type on the right. Arrays are treated as pointers in this context and only the base address is printed. Strings print the entire sequence of characters. By default, complex types such as structs cannot be printed with a single insertion operation, you must output each of the struct members one by one. Several insertions can be chained together by multiple uses of the insertion operator. The manipulator endl is used to output a newline. Values are formatted according to the stream’s default rules unless you specify otherwise. For explicit control, you insert I/O manipulators to set the field width, alignment, precision, and other features on a per-stream basis. A few common output manipulators options are described in the section on “Simple input and output” in Chapter 1.

Although the mechanisms for formatted I/O in any programming language can be quite useful, they also tend to be detail-ridden. I recommend having a reference on hand for looking up details on as-needed basis rather than memorizing the entirety of the options.

https://www.cas.mcmaster.ca/~qiao/courses/cs2so3/textbook/ProgAbs.pdf

1.1. File

A file is a self-contained piece of information available to the operating system and

any number of individual programs. A computer file can be thought of much like a

traditional file that one would find in an office’s file cabinet. Just like an office file,

information in a computer file could consist of basically anything.

Whatever program uses an individual file is responsible for understanding its

contents. Similar types of files are said to be of a common “format.” In most cases,

the easiest way to determine a file’s format is to look at the file’s extension.

Each individual file in Windows will also have a file attribute which sets a condition

to the specific file. For example, you can’t write new information to a file that has

the read-only attribute turned on.

A file name is just the name that a user or program gives the file to help identify what

it is. An image file may be named something (example of file name with extension:

kids-lake-2017.jpg). The name itself doesn’t affect the contents of the file, so even

if a video file is named something like image.mp4, it doesn’t mean it’s suddenly a

picture file.

Files in any operating system are stored on hard drives, optical drives, and other

storage devices. The specific way a file is stored and organized is referred to as a file

system.

Examples of Files:

An image copied from a camera to a computer may be in the JPG or TIF format.

These are files in the same way that videos in the MP4 format, or MP3 audio files, are

files. The same holds true for DOC/DOCX files used with Microsoft Word, TXT files

that hold plain text information, etc.

Though files are contained in folders for organization (like the photos in your Pictures

folder or music files in your iTunes folder), some files are in compressed folders, but

they’re still considered files. For example, a ZIP file is basically a folder that holds

other files and folders but it actually acts as a single file.

Another popular file type similar to ZIP is an ISO file, which is a representation of a

physical disc. It’s just a single file but it holds all the information found on a disc, like

a video game or movie.

From these few examples, it is clear that not all files are alike, but they all share a

similar purpose of holding information together in one place.

1. 2 Types of files:

a. A. Binary Files

Binary files typically contain a sequence of bytes, or ordered groupings of eight bits.

When creating a custom file format for a program, a developer arranges these bytes

into a format that stores the necessary information for the application. Binary file

formats may include multiple types of data in the same file, such as image, video,

and audio data. This data can be interpreted by supporting programs, but will show

up as garbled text in a text editor. Below is an example of a .PNG image file opened

in an image viewer and a text editor.

As it is seen, the image viewer recognizes the binary data and displays the

picture. When the image is opened in a text editor, the binary data is converted

to unrecognizable text. However, some of the text is readable. This is because the

PNG format includes small sections for storing textual data. The text editor, while

not designed to read this file format, still displays this text when the file is opened.

Many other binary file types include sections of readable text as well. Therefore, it

may be possible to find out some information about an unknown binary file type by

opening it in a text editor.

Binary files often contain headers, which are bytes of data at the beginning of a

file that identifies the file’s contents. Headers often include the file type and other

descriptive information. For example, in the image above, the “PNG” text indicates

the file is a PNG image. If a file has invalid header information, software programs

may not open the file or they may report that the file is corrupted.

b. Text Files

Text files are more restrictive than binary files since they can only contain textual

data. However, unlike binary files, they are less likely to become corrupted. While

a small error in a binary file may make it unreadable, a small error in a text file may

simply show up once the file has been opened. This is one of reasons Microsoft

switched to a compressed text-based XML format for the Office 2007 file types.

Text files may be saved in either a plain text (.TXT) format or rich text (.RTF) format. A

typical plain text file contains several lines of text that are each followed by an Endof-

Line (EOL) character. An End-of-File (EOF) marker is placed after the final character,

which signals the end of the file. Rich text files use a similar file structure, but may also

include text styles, such as bold and italics, as well as page formatting information.

Both plain text and rich text files include a (character encoding| character encoding)

scheme that determines how the characters are interpreted and what characters

can be displayed.

Since text files use a simple, standard format, many programs are capable of reading

and editing text files. Common text editors include Microsoft Notepad and WordPad,

which are bundled with Windows, and Apple TextEdit, which is included with Mac

OS X.

c. The difference between binary and text files

All files can be categorized into one of two file formats: binary or text. The two

file types may look the same on the surface, but they encode data differently. While

both binary and text files contain data stored as a series of bits (binary values of

1s and 0s), the bits in text files represent characters, while the bits in binary files

represent custom data.

While text files contain only textual data, binary files may contain both textual and

custom binary data.

Structures in C++

 A structure is a collection of simple variables. The variables in a structure can be of different types: int, float, and so on. The data items in a structure are called the members of the structure. In fact, the syntax of a structure is almost identical to that of a class. A structure is a collection of data, while a class is a collection of both data and functions. Structures in C++ similar to records in Pascal.

A Simple Structure (user-defined data types) The company makes several kinds of widgets, so the widget model number is the first member of the structure. The number of the part itself is the next member, and the final member is the part‟s cost. The next program defines the structure part, defines a structure variable of that type called part1. Assigns values to its members, and then displays these values.

A Simple Structure (user-defined data types) The company makes several kinds of widgets, so the widget model number is the first member of the structure. The number of the part itself is the next member, and the final member is the part‟s cost. The next program defines the structure part, defines a structure variable of that type called part1. Assigns values to its members, and then displays these values. #include using namespace std; struct part //declare a structure

 { int modelnumber; //ID number of widget int partnumber; //

ID number of widget part float cost;

//cost of part

}; int main() { part part1; //define a structure variable part1.modelnumber = 6244;

//give values to structure members part1.partnumber = 373;

part1.cost = 217.55F; //display structure members

cout << “Model “ << part1.modelnumber;

 cout << “, part “ << part1.partnumber;

 cout << “, costs $” << part1.cost << endl; return 0; }

 The program‟s output looks like this: Model 6244, part 373, costs $217.55

https://elearning.reb.rw/course/section.php?id=5366

References:

https://resources.jetbrains.com/storage/products/cpp/books/Cplusplus_Today.pdf

https://www.stroustrup.com/3rd_tour2.pdf

https://cdn.bookey.app/files/pdf/book/en/the-c—standard-library.pdf

https://www.cesarkallas.net/arquivos/livros/informatica/cpp/The%20C%2B%2B%20Standard%20Library.pdf

Leave a Comment

Your email address will not be published. Required fields are marked *