Using the C++ Math Library | ![]() ![]() |
Input and Output
MATLAB programs use scanf()
and fprintf()
to read and write from input and output and load()
and save()
to read and write array variables from and to MAT-files. C++ introduces a new concept: input and output streams. The MATLAB C++ Math Library supports MATLAB's fscanf()
and fprintf()
style of input and output along with load()
and save()
, and also provides the necessary operators for C++ stream input and output.
The MATLAB and MATLAB C++ Math Library versions of the fprintf()
and fscanf()
style functions are essentially the same. See Example - Using File I/O Functions (ex6.cpp) in Chapter 8 for more information on the input and output functions. The MATLAB C++ Math Library versions of load()
and save()
allow you to share data with MATLAB applications or with other applications developed with the MATLAB C++ or C Math Library; however they do not provide as many options as the MATLAB versions. See Importing and Exporting MAT-File Data in Chapter 8 to learn how the functions differ.
In many ways, streams are more convenient than functions like fprintf()
, because they are more consistent, flexible, and extensible. There are two basic types of streams, input streams and output streams. A C++ stream is a sequence of data objects. Often a stream consists of a sequence of characters. Streams can be attached to one of many types of data sources, or sinks: files, strings, and the screen, for example.
Each object in a C++ program is responsible for printing itself to a stream and reading itself from a stream. This decentralizes the responsibility for input and output formats, which means objects have complete control over their own printed format, and new objects can be added without changing the code in the basic streams mechanism. Furthermore, since the interface to each type of stream is the same, the code to save an object into a file is identical to that used to print that object on the screen or send it over the network to another process.
C++ defines three standard streams, cin
, cout
, and cerr
. cin
is bound to standard input, cout
to standard output and cerr
to standard error. To send an array A
to the standard output, you write:
cout << A << endl;
To read an array in from standard input, you write:
cin >> A;
To send an array A
to standard error, you write:
cerr << A << endl;
<<
is the output operator and >>
the input operator. The direction in which the operator points suggests the direction in which data flows. Using Array Stream I/O in Chapter 8 describes C++ stream-style output and the array I/O format completely. Refer to that section for more information.
![]() | Functions | Errors | ![]() |